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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…