简体   繁体   English

两种方法对实例方法的引用之间的区别

[英]Difference between the two method references to instance methods

import java.util.List;
import java.util.function.*;

interface SomeTest <T>
{
    boolean test(T n, T m);
}

class MyClass <T>
{
    boolean myGenMeth(T x, T y)
    {
        boolean result = false;
        // ...
        return result;
    }
}

class Timepass
{
    public static void main(String args[])
    {
        SomeTest <Integer> mRef = MyClass <Integer> :: myGenMeth;   //Statement 1

        Predicate <List<String>> p = List<String> :: isEmpty;       //Statement 2
    }
}

My query 我的查询

In the above code, Statement 1 produces two compile time errors 在上面的代码中, Statement 1产生两个编译时错误

1- Can not find method myGenMeth(Integer, Integer) 1-找不到方法myGenMeth(Integer, Integer)

2- Non static method myGenMeth(T, T) can not be referenced from static context 2-无法从静态上下文引用非静态方法myGenMeth(T, T)

Where as, Statement 2 shows no error. 其中, Statement 2没有显示错误。

1- What is the difference between Statement 1 and Statement 2 ?? 1- Statement 1Statement 2什么区别?

2- How the Statement 2 is working fine. 2- Statement 2的运作情况良好。

(I am not asking why the Statement 1 is producing error). (我不是问Statement 1为何产生错误)。

Because you have method references to instance methods, but don't specify any specific instance, the instance needs to be passed as a parameter to the interface method. 因为您具有对实例方法的方法引用,但未指定任何特定实例,所以需要将实例作为参数传递给接口方法。

For statement 2, you can pass this instance to the test method of Predicate : 对于语句2,您可以将此实例传递给Predicatetest方法:

p.test(new ArrayList<>());

But for statement 1, test doesn't take an instance as a parameter: 但是对于语句1, test不将实例作为参数:

mRef.test(new MyClass<>(), 1, 2);

To make this compile, SomeTest needs to be changed to: 为了进行此编译,需要将SomeTest更改为:

interface SomeTest<T> {
    boolean test(MyClass<T> instance, T n, T m);
}

Alternatively, you can make the method references refer to specific instances, then the interface method doesn't need to contain that parameter: 另外,您可以使方法引用引用特定的实例,然后接口方法不需要包含该参数:

SomeTest <Integer> mRef = new MyClass<Integer>()::myGenMeth;
mRef.test(1, 2);

Supplier<Boolean> p = new ArrayList<>()::isEmpty;
p.get();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM