I am trying to deal with Java8 method references and encountered very strange compile error.
I had a map with object values and I want to provide for user to apply some functions on values.
So I used generic method which takes map key and functional interface as parameter
And I am wondering why I don't need to cast Method reference to precise real type (in case of trim)
import java.util.HashMap;
import java.util.Map;
import java.util.function.UnaryOperator;
public class ReferenceDiscovering {
Map<String, Object> values = new HashMap<>();
public static void main(String[] args) {
ReferenceDiscovering main = new ReferenceDiscovering();
main.values.put("key1", " some text with space in start");
main.values.put("key2", "AAAAAAAAAAAAAA");
System.out.println(main.values);
main.applyFunctionByKey("key1", String::trim);
// cannot resolve method toLowerCase
// COMPILE ERROR HERE. WHY???? WHY NOT FOR trim?
// main.applyFunctionByKey("key2", String::toLowerCase);
main.applyFunctionByKey("key2", (UnaryOperator<String>)String::toLowerCase);
System.out.println(main.values);
}
private <T> void applyFunctionByKey(String key, UnaryOperator<T> binaryOperator) {
if (values.containsKey(key)) {
values.put(key, binaryOperator.apply((T)values.get(key)));
}
}
}
Result:
{key1= some text with space in start, key2=AAAAAAAAAAAAAA} {key1=some text with space in start, key2=aaaaaaaaaaaaaa}
toLowerCasehas two overloads, but we can't tell without the error. Please edit your question and include that.