我看不出我如何将Object
转换为ArrayList<Account>
,就像我所序列化的那样,它的类型为ArrayList<Accounts>
。正如我所看到的,这个代码应该可以工作不安全的铸造问题,如何投入类型安全?
当前反序列代码:
ArrayList<Accounts> alst = new ArrayList<Accounts>();
try {
ObjectInputStream ain = new ObjectInputStream(new BufferedInputStream(new FileInputStream("accounts.ser")));
Object o = ain.readObject();
if(o instanceof ArrayList) {
alst = (ArrayList<Accounts>) o;
}
else {
System.out.println("Big problem!!!");
}
ain.close();
}
我得到的问题:
warning:
[unchecked] unchecked cast
required: ArrayList<Account>.
found: Object
我看了一下这个问题这么多的职位,但我不能得到它的工作对我的问题。我一直在这个问题上喋喋不休,只是没有运气!我知道这是我对文件进行反序列化时遇到的问题。如何从对象中恢复到以前的类型?
还有别的办法吗?
将ain.close放入finally语句或使用Java 7:http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html – rethab
您无法在此处进行类型安全性转换。编译器无法知道在磁盘上的文件中存储了什么类型,并且转换为'ArrayList >'会很麻烦。只要压制警告。 – millimoose