Java 8对静态方法与实例方法的引用 [英] Java 8 reference to a static method vs. instance method

查看:110
本文介绍了Java 8对静态方法与实例方法的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下代码

public class A {
    int x;
    public boolean is() {return x%2==0;}
    public static boolean is (A a) {return !a.is();}
}

和另一个班级......

and in another 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类型表示法引用实例方法版本?非常感谢

the question is how do I refer to the instance method version using the A::is type notation? Thanks a lot

推荐答案

在您的示例中,静态和非静态方法都适用于过滤器的目标类型方法。在这种情况下,您不能使用方法引用,因为无法解决歧义。参见§15.13.1编译 - 时间声明方法参考以获取详细信息,特别是以下引用和以下示例:

In your example, both the static and the non-static method are applicable for the target type of the filter method. In this case, you can't use a method reference, because the ambiguity can not be resolved. See §15.13.1 Compile-Time Declaration of a Method Reference for details, in particular the following quote and the examples below:


如果第一次搜索产生一个静态方法,并没有适用的非静态方法[..],那么编译时声明是第一次搜索的结果。否则,如果没有静态方法适用[..],并且第二次搜索产生非静态方法,则编译时声明是第二次搜索的结果。 否则,没有编译时声明。

在这种情况下,您可以使用lambda表达式而不是方法参考:

In this case, you can use a lambda expression instead of a method reference:

a.stream().filter(item -> A.is(item));

关于搜索静态和非静态方法的上述规则有点特殊,因为它没有'重要的是,哪种方法更合适。即使静态方法采用 Object 而不是 A ,它仍然是模棱两可的。出于这个原因,我建议作为一般指导:如果一个类中有多个具有相同名称的方法(包括从基类继承的方法):

The above rule regarding the search for static and non-static methods is somewhat special, because it doesn't matter, which method is the better fit. Even if the static method would take an Object instead of A, it's still ambiguous. For that reason, I recommend as a general guideline: If there are several methods with the same name in a class (including methods inherited from base classes):


  • 所有方法应该具有相同的访问修饰符,

  • 所有方法都应该具有相同的final和abstract修饰符,

  • 并且所有方法都应该具有相同的静态修饰符

这篇关于Java 8对静态方法与实例方法的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆