這種失敗在Java 7中編譯:泛型類型推斷不適用於方法鏈接?
class Map<K,V> {
static <K,V> Map<K,V> empty() {return null;}
Map<K,V> put(K k, V v) {return null;}
V get(K k) {return null;}
}
class A {
static void f(Map<Integer,String> m){}
public static void main(String[] args) {
f(Map.empty());
}
}
它並不推斷Map
從Map.empty()
返回的具體類型:
$ javac7 A.java
A.java:10: error: method f in class A cannot be applied to given types;
f(Map.empty());
^
required: Map<Integer,String>
found: Map<Object,Object>
reason: actual argument Map<Object,Object> cannot be converted to Map<Integer,String> by method invocation conversion
1 error
,如果你改變了f
調用f(Map.<Integer,String>empty());
編譯。在Java 8中,它不需要訴諸這些。
但是,如果您將f
調用更改爲f(Map.empty().put(1,"A").put(2,"B"));
,則無法在Java 7和8上再次編譯。爲什麼?
$ $javac7 A.java
A.java:10: error: method f in class A cannot be applied to given types;
f(Map.empty().put(1,"A").put(2,"B"));
^
required: Map<Integer,String>
found: Map<Object,Object>
reason: actual argument Map<Object,Object> cannot be converted to Map<Integer,String> by method invocation conversion
1 error
$ $javac8 A.java
A.java:10: error: incompatible types: Map<Object,Object> cannot be converted to Map<Integer,String>
f(Map.empty().put(1,"A").put(2,"B"));
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error
$ $javac8 -Xdiags:verbose A.java
A.java:10: error: method f in class A cannot be applied to given types;
f(Map.empty().put(1,"A").put(2,"B"));
^
required: Map<Integer,String>
found: Map<Object,Object>
reason: argument mismatch; Map<Object,Object> cannot be converted to Map<Integer,String>
1 error
只是使它'靜態地圖空(){返回NULL;}',它不喜歡你將使用泛型反正任何修飾。 –