In diesem Code-Snippet meine IDE (IDEA Intellij Community) schlägt vor, Methodenreferenz auf Funktionsschnittstelle zu werfen.Warum benötigt die Methodenreferenz eine Typumwandlung in eine Funktionsschnittstelle?
Warum ist das?
public class MethodReferences {
public static void main(String[] strings) {
Function<String, Integer> f = Integer::parseInt;
Predicate<Person> personPredicate = p->convert(p.getAge(),Integer::parseInt) >10;
//This is fine
System.out.println(convert("123", f));
//This is fine
System.out.println(convert("123", (Function<String, Integer>) Integer::parseInt));
//This is NOT
System.out.println(convert("123", Integer::parseInt)); //x1
}
private static <T, S> T convert(S s, Function<S, T> stFunction) {
return stFunction.apply(s);
}
}
Die Fehlermeldung, die ich in Zeile erhalten x1
ist:
Error:(20, 19) java: reference to println is ambiguous
both method println(char[]) in java.io.PrintStream and method println(java.lang.String) in java.io.PrintStream match
Error:(20, 35) java: incompatible types: inferred type does not conform to upper bound(s)
inferred: java.lang.Integer
upper bound(s): char[],java.lang.Object
Ich denke, es hat etwas damit zu tun, dass "Integer :: parseInt" eine "int" anstelle einer "Integer" liefert – Aaron
Ich kann dies mit JDK 1.8.0_51 nicht reproduzieren. Mein Code kompiliert und gibt die Ausgabe. Welche Version von JDK verwenden Sie? – SMA
@SMA der Code ist nicht kompilierbar ... – Adelin