繁体   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
    }
}

我的查询

在上面的代码中, Statement 1产生两个编译时错误

1-找不到方法myGenMeth(Integer, Integer)

2-无法从静态上下文引用非静态方法myGenMeth(T, T)

其中, Statement 2没有显示错误。

1- Statement 1Statement 2什么区别?

2- Statement 2的运作情况良好。

(我不是问Statement 1为何产生错误)。

因为您具有对实例方法的方法引用,但未指定任何特定实例,所以需要将实例作为参数传递给接口方法。

对于语句2,您可以将此实例传递给Predicatetest方法:

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

但是对于语句1, test不将实例作为参数:

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

为了进行此编译,需要将SomeTest更改为:

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

另外,您可以使方法引用引用特定的实例,然后接口方法不需要包含该参数:

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