this::myMethod
refers to myMethod
on a specific instance of ClassName
- the instance that you put this::myMethod
in its code.
ClassName::myMethod
can refer to either a static method or an instance method. If it refers to an instance method, it may be executed on a different instance of ClassName
each time it is called.
For example:
List<ClassName> list = ...
list.stream().map(ClassName::myMethod)...
will execute myMethod
each time for a different ClassName
member of the list.
Here's a mode detailed example that shows the difference between these two type of method reference:
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 ();
}
}
Output:
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()