Same Java method referenced but different address returned

I refer to the same method twice, but the links are different. See this example:

import java.util.function.Consumer;

public class MethodRefTest {
    public static void main(String[] args) {
        new MethodRefTest();
    }

    public MethodRefTest() {
        Consumer<Integer> a = this::method;
        System.out.println(a);
        Consumer<Integer> b = this::method;
        System.out.println(b);
    }

    public void method(Integer value) {

    }
}

Conclusion:

MethodRefTest$$Lambda$1/250421012@4c873330
MethodRefTest$$Lambda$2/295530567@776ec8df

Is a method a reference nothing more than syntactic sugar for anonymous classes? If not, what should I do to always get the same method reference? (Besides storing the link once in a field to work with.)

(Appendix: I thought of method references as a prettier way to implement an observer, but with different references every time it is impossible to remove an observer from an observable after adding it.)

+4
source share
4 answers

Is a method a reference nothing more than syntactic sugar for anonymous classes?

. , , .

, , ? ( .)

. . ( .)

+3

,

?

JLS ,

(JLS 8, 15.13)

, , . , .

, , , , . , , JLS, , , .

,

, , ? ( .)

, , . , @JohnKugelman, , , , .

+1

() .

0

, toString() , , , - . , -, . - a==b.

, , . - , ?, JVM , HotSpot/OpenJDK , this::method - this. , , this::method .

Java 8?, , . , , - . , , , , - .

0

Source: https://habr.com/ru/post/1687049/


All Articles