El siguiente códigoBug en compilador Eclipse o en javac ("parámetros de tipo de T no pueden determinarse")
public class GenericsTest2 {
public static void main(String[] args) throws Exception {
Integer i = readObject(args[0]);
System.out.println(i);
}
public static <T> T readObject(String file) throws Exception {
return readObject(new ObjectInputStream(new FileInputStream(file)));
// closing the stream in finally removed to get a small example
}
@SuppressWarnings("unchecked")
public static <T> T readObject(ObjectInputStream stream) throws Exception {
return (T)stream.readObject();
}
}
compila en eclipse, pero no con javac (parámetros de tipo de T no pueden determinarse; no único la instancia máxima existe para la variable de tipo T con límites superiores T, java.lang.Object).
Cuando cambio readObject (archivo String) para
@SuppressWarnings("unchecked")
public static <T> T readObject(String file) throws Exception {
return (T)readObject(new ObjectInputStream(new FileInputStream(file)));
}
se compila en Eclipse y con javac. ¿Quién está correcto, el compilador de eclipse o javac?
return GenericsTest2. readObject (nuevo ObjectInputStream (nuevo FileInputStream (archivo))); funciona. ¡Gracias! –
No estoy de acuerdo, se parece más al error relacionado a continuación. El compilador debe confiar en una conversión explícita y sin inferencia de tipos - la siguiente compila bien @SuppressWarnings ("sin marcar") pública estática T createT (String className) throws Exception { de retorno (T) Class.forName (className) .newInstance(); } –