编写一个读取二进制文件的方法
我想编写一个从二进制文件读取对象的方法,但我想使用泛型来概括它。
我有这段代码:
@SuppressWarnings ("unchecked")
public static <T> T readFromBinaryFile (String filename){
T obj = null;
if (FileUtils.existsFile (filename)){
ObjectInputStream ois = null;
try{
ois = new ObjectInputStream (new FileInputStream (filename));
obj = (T)ois.readObject ();
}catch (IOException e){
Debug.out (e);
}catch (ClassNotFoundException e){
Debug.out (e);
}finally{
try{
if (ois != null) ois.close();
}catch (IOException e){
Debug.out (e);
}
}
}
return obj;
}
当我执行它时,我得到一个 ClassCastException。我对java中的模板一无所知,所以任何信息都会受到赞赏。我读过一些与擦除、编译时和执行时相关的内容,但我不太明白为什么会出现这个 ClassCastException。
谢谢。
编辑:我这样调用该方法: FileUtils.readFromBinaryFile(文件名);
(不带“”)
I want to write a method that reads an object from a binary file but I want to generalize it using generics.
I have this code:
@SuppressWarnings ("unchecked")
public static <T> T readFromBinaryFile (String filename){
T obj = null;
if (FileUtils.existsFile (filename)){
ObjectInputStream ois = null;
try{
ois = new ObjectInputStream (new FileInputStream (filename));
obj = (T)ois.readObject ();
}catch (IOException e){
Debug.out (e);
}catch (ClassNotFoundException e){
Debug.out (e);
}finally{
try{
if (ois != null) ois.close();
}catch (IOException e){
Debug.out (e);
}
}
}
return obj;
}
When I execute it I get a ClassCastException. I don't know anything about templates in java so any information will be apreciated. I've read something related to erasure, compile-time and execution-time but I don't understand very well why I get this ClassCastException.
Thanks.
EDIT: I call the method like this:FileUtils.readFromBinaryFile (filename);
(Without "")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Java中有模板吗?只需使用 Object 而不是 T。在 Java 中,一切都从基础上派生自 Object,因此您不需要 T obj,而是 Object obj。
Are there templates in Java? Just use Object instead of T. In Java everything derives from Object at the base, so you don't want T obj but Object obj.
ClassCastException 意味着您读取的类型与您期望的类型(并转换为)不匹配。我建议您查看在调试器(或日志消息)中读取的对象,并将其与您期望的类型进行比较。
A ClassCastException means the type you read didn't match the type you were expecting (and cast to) I suggest you see which object you are read in a debugger (or a log message) and compare it with what you are expecting.
你调用的方法是错误的。
只需这样做:
您所调用的是所谓的泛型方法。
“我们不必将实际类型参数传递给泛型方法。编译器会根据实际参数的类型为我们推断类型参数。它通常会推断出最具体的类型参数,从而使调用类型正确。” 源
编辑:
我已经尝试过你的例子并且它有效(我实际上评论了一些行)
You're calling your method wrong.
Just do it this way:
What you're calling is so-called generic method.
"We don't have to pass an actual type argument to a generic method. The compiler infers the type argument for us, based on the types of the actual arguments. It will generally infer the most specific type argument that will make the call type-correct." source
EDIT:
I've tried your example and it works (I had actually comment some lines)