java - this::myMethod 和 ClassName::myMethod 之间有什么区别?

标签 java java-8 method-reference

我不明白这两者的区别

this::myMethod  

ClassName::myMethod

thisClassName 类的实例时。

我认为在这两种情况下我都调用方法 myMethod 并将我运行的 myObject 作为 myMethod 方法的参数,但是我认为是有区别的。这是什么?

最佳答案

this::myMethod 引用 ClassName 的特定实例上的 myMethod - 您放置 this::myMethod 的实例 在它的代码中。

ClassName::myMethod 可以引用静态方法或实例方法。如果它引用实例方法,则每次调用它时可能会在 ClassName 的不同实例上执行。

例如:

List<ClassName> list = ...
list.stream().map(ClassName::myMethod)...

每次都会为列表的不同 ClassName 成员执行 myMethod

下面是一个模式详细示例,显示了这两种类型的方法引用之间的区别:

public class Test ()
{
    String myMethod () {
        return hashCode() + " ";
    }
    String myMethod (Test other) {
        return hashCode() + " ";
    }
    public void test () {
        List<Test> list = new ArrayList<>();
        list.add (new Test());
        list.add (new Test());
        System.out.println (this.hashCode ());
        // this will execute myMethod () on each member of the Stream
        list.stream ().map (Test::myMethod).forEach (System.out::print);
        System.out.println (" ");
        // this will execute myMethod (Test other) on the same instance (this) of the class
        // note that I had to overload myMethod, since `map` must apply myMethod
        // to each element of the Stream, and since this::myMethod means it
        // will always be executed on the same instance of Test, we must pass
        // the element of the Stream as an argument
        list.stream ().map (this::myMethod).forEach (System.out::print);
    }
    public static void main (java.lang.String[] args) { 
        new Test ().test ();
    }
}

输出:

2003749087 // the hash code of the Test instance on which we called test()
1747585824 1023892928  // the hash codes of the members of the List
2003749087 2003749087 // the hash code of the Test instance on which we called test()

关于java - this::myMethod 和 ClassName::myMethod 之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46520821/

相关文章:

java - 方法引用 Bound Receiver 和 Unbound Receiver 的区别

java - Android简单程序-SeekBar未创建

Javamail 作为 tomcat 中的 JNDI 资源

java - Java 8 中流的笛卡尔积作为流(仅使用流)

datetime - JPA2 标准和 Java 8 日期和时间 API

java - 是否有可用于抛出异常的方法引用?

java - 是否有一种方法引用方式来表达一个什么都不做的(Runnable)lambda?

java - 使用 Mockito、TestNG 和 OpenEJB 对 EJB 进行单元测试

java - 使用 gradle 依赖于 Java 9 Module System 库中的遗留 jar

java - 如何使用 Hibernate 映射 java.time.Year 和其他 java.time 类型