I am learning method references in Java 8. I learnt that we can define functional interface method with either lambda or method reference.
Method reference is a way of telling "there exist a similar method with same signature of functional interface method, you can call it".
Further if that similar looking method exists as a static method, we call it using its class name. Or if it exists as non static way, then we will call it with object.
I am confused with below code.. EatSomething class has non-static similarToEat method, then why it is being called like a static method?
import java.util.function.*;
public class Test {
public static void main(String[] args) {
Test test = new Test();
EatSomething es = new EatSomething();
Function <EatSomething,String> ff1 = EatSomething::similarToEat; //here.. similarToEat is a non-static method, then why do I need to call it using class name?
Function <EatSomething,String> ff2 = (EatSomething eat)->eat.similarToEat();
Function <EatSomething,String> ff3 = es::eatOverloaded;
System.out.println(test.process(ff1));
}
private String process(Function<EatSomething,String> func) {
EatSomething es = new EatSomething();
return func.apply(es);
}
}
class EatSomething{
public String similarToEat() {
return "eat lightning, and crap thunder ";
}
public String eatOverloaded(EatSomething es) {
return es.similarToEat();
}
}
I am totally confused with this. Why should't I call similarToEat using object. Why do I have to use class name here? I can easily relate ff2 and ff3 objects in above code. Really confused with ff1.
One more piece of code..
interface MyCustomFunction{
String test(String abc);
}
public class MethodReference {
public static void main(String[] args) {
MethodReference mr = new MethodReference();
MyCustomFunction func = String::toUpperCase; //here again. Why are we calling toUpperCase with its class name when its a non-static method
System.out.println(mr.processs(func));
}
public String processs(MyCustomFunction obj) {
return obj.test("abc");
}
}
EatSomethingclass. It only runs when explicitly invoked on an instance ofEatSomethinginside theprocessmethod. Also this is horrible code, never write something like this =DMyCustomFunction func = String::toUpperCase;hereMyCustomFunctionhas a method lets sayString test(String abc);buttoUpperCaseis a non static method. Then why are we callingtoUpperCasewith its class name i.e. String.::. The docs for which have already been linked to in the answer you accepted.public String extractUsername(String token) { // TODO Auto-generated method stub Function<Claims,String> func = (Claims c)->c.getSubject(); // or Claims::getSubject return extractClaim(token,func); }here a implemented method of Claims interface getSubject is called as if it is a static method.(Object o)->o.someMethod()can be further shortened toObject::someMethodwill remember that.