以下代码:
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();
}
}
在Eclipse中编译正常,但使用javac编译时出现错误(无法确定类型参数T;不存在满足类型变量T上限T、java.lang.Object的唯一最大实例)。
当我将readObject(String file)更改为
@SuppressWarnings("unchecked")
public static <T> T readObject(String file) throws Exception {
return (T)readObject(new ObjectInputStream(new FileInputStream(file)));
}
代码可以在Eclipse和通过Javac编译器编译。哪个是正确的,Eclipse编译器还是Javac编译器?
@SuppressWarnings("unchecked") public static T createT(String className) throws Exception {
return (T) Class.forName(className).newInstance();
}
- Duncan McGregor