Java 8 引用静态方法与实例方法

标签 java java-8 java-stream method-reference

假设我有以下代码

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/

相关文章:

swing - mac os Sierra 更新后面临 Intellij 等 Java 应用程序的滚动问题

java - LocalDateTime 解析错误(Java 8)

Java 8 : Stream, NIO 和 Lambda

java - Thrift 服务与 RESTful 服务哪个更好?

java - 如何在指定索引处插入值?

java - 将数组复制到同一个数组

java - getRuntime().exec() 什么都不做

java - 将7/2除以3.5,但是为什么在第一种情况下没有显示不兼容错误,而在第二种情况下又为什么不显示.5呢?

recursion - 使用 Java 8 Streams 求和树节点

java - 如何从 Java 8 的学生列表中的列表中找到前 n 个最受欢迎的运动