这个:: myMethod和ClassName :: myMethod之间的差异是什么?

T.S*_*T.S 2 java java-8 method-reference

我不明白之间的区别

this::myMethod  
Run Code Online (Sandbox Code Playgroud)

ClassName::myMethod
Run Code Online (Sandbox Code Playgroud)

ClassName类的实例时.

我认为在这两种情况下我都会调用该方法myMethod并将myObject其作为myMethod方法的参数运行,但我认为存在差异.它是什么?

Era*_*ran 6

this::myMethod指的是您在其代码中放置的实例myMethod的特定实例.ClassNamethis::myMethod

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

例如:

List<ClassName> list = ...
list.stream().map(ClassName::myMethod)...
Run Code Online (Sandbox Code Playgroud)

myMethod每次执行ClassName列表的不同成员.

这是一个模式详细示例,显示了这两种方法参考之间的区别:

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 ();
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

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()
Run Code Online (Sandbox Code Playgroud)