在 Android Java 代码中使用泛型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3810854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using generics in Android Java code
提问by codedog
I'm a newbie in Java so I'm not sure if this is possible. Basically I need to de-serialise a file into an object of a given type. Basically the method will do this:
我是 Java 新手,所以我不确定这是否可行。基本上我需要将文件反序列化为给定类型的对象。基本上该方法会这样做:
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(fis);
MyClass newObject = (MyClass)in.readObject();
in.close();
return newObject;
I would like this method to be generic, therefore I can tell it what type I want to in.readObject()
to cast its output into, and return it.
我希望这个方法是通用的,因此我可以告诉它我想in.readObject()
将它的输出转换成什么类型,然后返回它。
Hope this makes sense...then again, I probably didn't understand generics properly and this is not actually possible, or advisable.
希望这是有道理的......再说一次,我可能没有正确理解泛型,这实际上是不可能的,或者是可取的。
Thanks, D.
感谢:D。
回答by Andrei Fierbinteanu
I'm not sure about Android (or any limitations it might have), but in Java you can do something like this:
我不确定 Android(或它可能有的任何限制),但在 Java 中,您可以执行以下操作:
public static <T> T getObject(String filename) throws IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(fis);
T newObject = (T) in.readObject();
in.close();
return newObject;
}
and then call it like
然后称之为
MyClass myObj = getObject("in.txt");
This will give you an unchecked cast warning though, since the compiler can't be sure you can cast the object received to the type provided, so it's not exactly type safe. You need to be sure that what you're getting from the input stream actually can be cast to that class, otherwise you will get a ClassCastException. You can suppress the warning by annotating the method with @SuppressWarnings("unchecked")
这会给你一个未经检查的强制转换警告,因为编译器不能确定你可以将接收到的对象强制转换为提供的类型,所以它不是完全类型安全的。您需要确保从输入流中获得的内容实际上可以转换为该类,否则您将获得 ClassCastException。您可以通过注释方法来抑制警告@SuppressWarnings("unchecked")
回答by codedog
Having just seen this How do I make the method return type generic?I am going to try the following:
刚刚看到这个如何使方法返回类型通用?我将尝试以下操作:
public <T> T deserialiseObject(String filename, Class<T> type)
throws StreamCorruptedException, IOException,
ClassNotFoundException {
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(fis);
Object newObject = in.readObject();
in.close();
return type.cast(newObject);
}