我正在阅读Java 8 Method Reference: How to Use it并希望以其他方式重用 TriFunction:
public class Numbers {
public static void main(String[] args) throws Exception {
TriFunction<Numbers, String, String, Integer> function = (s, arg1, arg2 ) -> Numbers.doSum(arg1, arg2);
System.out.println(function.apply(new Numbers(), "1", "2"));
//error, not warning: The method doSum(String, String) from the type Numbers should be accessed in a static way
TriFunction<Numbers, String, String, Integer> mRef = Numbers::doSum;
System.out.println(mRef.apply(new Numbers(), "3", "4"));
}
static Integer doSum(String s1, String s2) {
return Integer.parseInt(s1) + Integer.parseInt(s2);
}
}
interface TriFunction<T, U, V, R> {
R apply(T t, U u, V v);
}
我知道静态方法应该以静态方式访问。但我认为我并没有违反 Numbers::doSum
的规则。那么原因是什么呢?
最佳答案
Numbers::doSum
,当应用于TriFunction<Numbers, String, String, Integer>
时,翻译为(n, s1, s2) -> n.doSum(s1, s2)
,这意味着您正在 Numbers
的实例上调用静态方法。要么将其设为实例方法,要么使用 BiFunction
这并不期望 Numbers
实例。
关于java - 为什么 eclipse 告诉我静态方法引用 ClassName::staticMethod 应该为 "accessed in a static way"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48778996/