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 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 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 comparator = Integer::compareTo;
Comparator 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?
解决方案
This is because lambdas are not from Object Oriented world.
When you assign some method to Comparator it's task is to perform the comparision.
Comparator methodOne = Integer::compare;
Comparator 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.