Java 8 function interface assignment context
The question is about the allocation background of the functional interface –
Predicate<String> p = String::isEmpty;
It works normally when the isempty method declaration in the string class is – public Boolean isempty() {}
If I try to declare the same in a custom class –
class Test{ public boolean isEmpty(){ ... } }
Do the same task –
Predicate<String> p = Test::isEmpty;
This will be a compilation error –
And predicate < T > represents a predicate of a parameter (Boolean function), and the function method is Boolean test (T, t) {}
Any explanation? Did I miss anything?
Solution
You should have:
Predicate<Test> p = Test::isEmpty;
Not at all
Predicate<String> p = Test::isEmpty;
No string
class Test { public boolean isEmpty(){ ... } }
So why predict < string >?
See tutorial of method references What you get here is the third case "instance method referencing any object of a specific type"
have
Predicate<String> p = String::isEmpty(); String s = "";
Call p.test (s); Same as call s.isempty(); So that's why you can't call a method from test with a string as a parameter
If both string and test use the method Boolean isempty() to implement the interface empty, and then use predicate < empty >, there may be a common predicate Then both p.test (string) and p.test (test) can work; Otherwise it won't. Java has powerful input and doesn't support duck typing