Java 什么';myMethod和ClassName::myMethod之间的区别是什么?

Java 什么';myMethod和ClassName::myMethod之间的区别是什么?,java,java-8,method-reference,Java,Java 8,Method Reference,我不明白他们之间的区别 this::myMethod 及 当时,此是类名类的实例 我认为在这两种情况下,我都调用了方法myMethod,并给出了作为myMethod方法的参数运行的myObject,但我认为这是不同的。它是什么?this::myMethod指的是ClassName的特定实例上的myMethod——您将this::myMethod放入其代码中的实例 ClassName::myMethod可以引用静态方法或实例方法。如果它引用一个实例方法,那么每次调用它时,它都可能在Class

我不明白他们之间的区别

this::myMethod  

时,此类名类的实例


我认为在这两种情况下,我都调用了方法
myMethod
,并给出了作为
myMethod
方法的参数运行的
myObject
,但我认为这是不同的。它是什么?

this::myMethod
指的是
ClassName
的特定实例上的
myMethod
——您将
this::myMethod
放入其代码中的实例

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

例如:

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

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

实例与类方法。。您在这个实例上执行myMethod的一个位置和在另一个位置一样,在类上执行myMethod可能会有所帮助。这取决于上下文。第一个在
上调用myMethod。第二个调用ClassName的静态方法myMethod,或者调用函数接口方法的参数上的实例方法(如
stream.forEach(ClassName::myMethod)
,这相当于
stream.forEach(obj->obj.myMethod())
。但是当我使用String::toUpperCase时,我会在实例上执行myMethod,它是toUpperCase,而不是类的可能副本。因此当我们使用this::myMethod时,我们会在this对象上调用该方法,并将集合中的每个对象作为参数传递给该方法?@T.S这是使用
this::myMethod
的一个示例。我不确定这是一个很好的例子,因为当我们调用
map
时,我们通常希望将流的一个元素转换为其他类型,因此使用Test::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()