我不明白
之间的区别this::myMethod
和
ClassName::myMethod
当此是 ClassName 类的实例时。
我认为在这两种情况下我都会调用方法myMethod
并将myObject
作为myMethod
方法的参数运行,但我认为存在差异。它是什么?
答案 0 :(得分:6)
this::myMethod
在myMethod
的特定实例上引用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()