this::myMethod 和 ClassName::myMethod 有什么区别?

What's the diffrence between this::myMethod and ClassName::myMethod?

我不明白

之间的区别
this::myMethod  

ClassName::myMethod

thisClassName 的实例时 class.

我认为在这两种情况下我都调用方法 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()