Tob*_*lte 74 java eclipse generics
以下代码
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();
}
}
Run Code Online (Sandbox Code Playgroud)
在eclipse中编译,但不在javac中编译(T的类型参数无法确定;对于具有上限T,java.lang.Object的类型变量T,不存在唯一的最大实例).
当我将readObject(String文件)更改为
@SuppressWarnings("unchecked")
public static <T> T readObject(String file) throws Exception {
return (T)readObject(new ObjectInputStream(new FileInputStream(file)));
}
Run Code Online (Sandbox Code Playgroud)
它在eclipse和javac中编译.谁是正确的,eclipse编译器还是javac?
Fab*_*eeg 66
我说这是Sun编译器在这里和这里报告的错误,因为如果你将你的行更改为下面的那一行,它就可以兼顾两者,这似乎正是错误报告中描述的内容.
return GenericsTest2.<T>readObject(new ObjectInputStream(new FileInputStream(file)));
Run Code Online (Sandbox Code Playgroud)
Chr*_*ung 13
在这种情况下,我会说你的代码是错误的(Sun编译器是对的).输入参数中没有任何内容readObject可以实际推断出类型T.在这种情况下,最好让它返回Object,并让客户端手动转换结果类型.
这应该工作(虽然我还没有测试过):
public static <T> T readObject(String file) throws Exception {
return GenericsTest2.<T>readObject(new ObjectInputStream(new FileInputStream(file)));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26206 次 |
| 最近记录: |