Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
566 views
in Technique[技术] by (71.8m points)

lambda with non-static methods in Java 8

I am trying to learnd lambdas in new Java 8. There is one interesting thing. If method has the same signature as functional interface, it can be assigned to it using lambdas API. For instance.

Comparator<Integer> myComp = Integer::compare;

This method(Integer.compare) is static, takes two values, everything is perfect. the signature the same as in interface method compare. BUT this can be made with non-static methods, for example

Comparator<Integer> myComp = Integer::compareTo.

This method is non-static (instance level) and furthermore, it takes only one value. As I have understood, there is no non-static methods in Java, every method is static but if it is not marked as static it takes this as the first parameter. As following

compareTo(this,Integer value).

It would be reasonable to assume that result will be undefined because of comparing object and integer. BUT THIS WORKS.

Comparator<Integer> comparator = Integer::compareTo;
Comparator<Integer> comparator2 = Integer::compare;
System.out.println(comparator.compare(1,2));
System.out.println(comparator2.compare(1,2));

This works equally. I have debugged call method stack. While calling method compare of comparator object without creating instance, this. Value is already initialized by the first parameter and of course this is valid reference to the object.

SO the question is How does this work? While calling method compiler checks, if the class has only one field which has the same type as first param in method, if class has compiler implictly creates new instance of the class with initialized field or how does it work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is because lambdas are not from Object Oriented world.

When you assign some method to Comparator<Integer> it's task is to perform the comparision.

Comparator<Integer> methodOne = Integer::compare;
Comparator<Integer> methodTwo = Integer::compareTo;

This methodOne.compare(1,2); will be translated to Integer.compare(1,2) it is called non-instance-capturing and refer to static method

This methodTwo.compare(1,2); will be translated to 1.compareTo(2) is is called instance-capturing and refers to instance methods.

Compiler "knows" what type of method you have referenced so it can process without error.

Method reference capture


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...