Il seguente programma viene compilato in Java 7 e in Eclipse Marte RC2 per Java 8:La variabile di inferenza ha limiti incompatibili. Regressione del compilatore Java 8?
import java.util.List;
public class Test {
static final void a(Class<? extends List<?>> type) {
b(newList(type));
}
static final <T> List<T> b(List<T> list) {
return list;
}
static final <L extends List<?>> L newList(Class<L> type) {
try {
return type.newInstance();
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Utilizzando il compilatore javac 1.8.0_45, viene segnalato il seguente errore di compilazione:
Test.java:6: error: method b in class Test cannot be applied to given types;
b(newList(type));
^
required: List<T>
found: CAP#1
reason: inference variable L has incompatible bounds
equality constraints: CAP#2
upper bounds: List<CAP#3>,List<?>
where T,L are type-variables:
T extends Object declared in method <T>b(List<T>)
L extends List<?> declared in method <L>newList(Class<L>)
where CAP#1,CAP#2,CAP#3 are fresh type-variables:
CAP#1 extends List<?> from capture of ? extends List<?>
CAP#2 extends List<?> from capture of ? extends List<?>
CAP#3 extends Object from capture of ?
Una soluzione è localmente assegnare una variabile:
import java.util.List;
public class Test {
static final void a(Class<? extends List<?>> type) {
// Workaround here
List<?> variable = newList(type);
b(variable);
}
static final <T> List<T> b(List<T> list) {
return list;
}
static final <L extends List<?>> L newList(Class<L> type) {
try {
return type.newInstance();
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
}
so che l'inferenza dei tipi è cambiata molto in Java 8 (e.g. due to JEP 101 "generalized target-type inference"). Quindi, questo è un bug o una nuova "funzione" linguistica?
EDIT: Ho anche segnalato questo a Oracle come JI-9.021.550, ma solo nel caso in cui questa è una "caratteristica" in Java 8, ho segnalato il problema anche a Eclipse:
hi Lukas, non chiamiamo ancora un bug di eclissi; per favore deseleziona la mia risposta :( – ZhongYu
@ bayou.io: hai ragione Fatto! –