我不明白这两者的区别
this::myMethod
和
ClassName::myMethod
当 this 是 ClassName 类的实例时。
我认为在这两种情况下我都调用方法 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/