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

时间:2017-10-02 07:03:14

标签: java java-8 method-reference

我不明白

之间的区别
this::myMethod  

ClassName::myMethod

ClassName 类的实例时。

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

1 个答案:

答案 0 :(得分:6)

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

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

例如:

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

每次都会对列表中不同的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 ();
    }
}

输出:

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()