为什么字段whyIsAnInstanceRequired
需要一个实例,为什么它不能像字段ERRwhyIsAnInstanceRequired
那样工作?
编译错误为:
Error: java: incompatible types: invalid method reference
unexpected instance method function(programming.java.FunctionalQuestion.Helper,programming.java.FunctionalQuestion) found in unbound lookup
查看代码:
package programming.java;
public class FunctionalQuestion {
class Helper{}
public void setValue (long value){}
java.util.function.ObjLongConsumer<FunctionalQuestion> whyIsAnInstanceNotRequired =
FunctionalQuestion::setValue;
public void function(Helper helper, FunctionalQuestion functionalQuestion) {}
java.util.function.BiConsumer<Helper, FunctionalQuestion> whyIsAnInstanceRequired =
new FunctionalQuestion()::function;
/*
* Error: java: incompatible types: invalid method reference
unexpected instance method function(programming.java.FunctionalQuestion.Helper,programming.java.FunctionalQuestion) found in unbound lookup
* */
java.util.function.BiConsumer<Helper, FunctionalQuestion> ERRwhyIsAnInstanceRequired =
FunctionalQuestion::function;
}
答案 0 :(得分:0)
我相信这可以解释为什么我对原始代码感到惊讶。
这个概念称为:
引用特定类型的任意对象的实例方法。
示例:ContainingType::methodName
,如以下内容所述:
methodreferences.html
从该文档:
以下是对特定类型的任意对象的实例方法的引用示例:
String[] stringArray
= { "Barbara", "James", "Mary", "John","Patricia", "Robert", "Michael", "Linda" };
Arrays.sort(stringArray, String::compareToIgnoreCase);
方法引用
String::compareToIgnoreCase
的等效lambda表达式将具有形式参数list (String a, String b)
,其中a和b是用于更好地描述此示例的任意名称。方法引用将调用方法a.compareToIgnoreCase(b)
。