假设我有以下代码
public class A {
int x;
public boolean is() {return x%2==0;}
public static boolean is (A a) {return !a.is();}
}
在另一个类(class)...
List<A> a = ...
a.stream().filter(b->b.isCool());
a.stream().filter(A::is);
//would be equivalent if the static method is(A a) did not exist
问题是如何使用 A::is 类型表示法来引用实例方法版本?非常感谢
最佳答案
在您的示例中,静态和非静态方法都适用于过滤器方法的目标类型。在这种情况下,您不能使用方法引用,因为无法解决歧义。见§15.13.1 Compile-Time Declaration of a Method Reference有关详细信息,特别是以下引用和以下示例:
If the first search produces a static method, and no non-static method is applicable [..], then the compile-time declaration is the result of the first search. Otherwise, if no static method is applicable [..], and the second search produces a non-static method, then the compile-time declaration is the result of the second search. Otherwise, there is no compile-time declaration.
在这种情况下,您可以使用 lambda 表达式代替方法引用:
a.stream().filter(item -> A.is(item));
上面关于搜索静态和非静态方法的规则有些特殊,因为哪个方法更合适并不重要。即使静态方法采用 Object 而不是 A,它仍然是不明确的。出于这个原因,我建议作为一般准则:如果一个类中有多个同名方法(包括从基类继承的方法):
- 所有方法都应该有相同的访问修饰符,
- 所有方法都应具有相同的 final 和 abstract 修饰符,
- 并且所有方法都应该有相同的静态修饰符
关于Java 8 引用静态方法与实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23051879/