【发布时间】:2014-02-27 22:55:51
【问题描述】:
ObjectInputStream 的 readObject() 方法返回 Object 并且需要为 casted 以匹配 type。如果我serialize 和array of String,我会得到array of Objects 还是Array of Strings。我在下面试过这个。 String[] arr = (String[]) objArr; 在一般情况下失败。
但是在Serialization 之后,当我将从readObject() 返回的Object 转换为String[] 时,我没有得到任何Exception。那返回的是什么?
readObject() 的方法签名是
public final Object readObject() throws IOException, ClassNotFoundException 表示它返回对象。
为什么将其转换为 String[] 在这里有效,但在更一般的情况下(如下所示)它会失败。
public class UpcastDownCast {
public static void main(String[] args) throws IOException, ClassNotFoundException {
//the below three lines give runtime Exception
Object[] objArr = {new String("hello"), new String("world")};
String[] arr = (String[]) objArr;
System.out.println(Arrays.toString(arr));
String[] arrV={new String("Car"), new String("Bike")};
FileOutputStream of= new FileOutputStream("file.ser");
ObjectOutputStream oos=new ObjectOutputStream(of);
oos.writeObject(arrV);
FileInputStream fi = new FileInputStream("file.ser");
ObjectInputStream ois= new ObjectInputStream(fi);
String[] t2= (String[]) ois.readObject();
System.out.println("after "+ Arrays.toString(t2));
}
}
【问题讨论】:
-
因为实例被转换为与它们起源相同的类型,就像人类一样,它们是公民。
标签: java arrays string serialization objectinputstream