ObjectInputStream
的readObject()
方法返回对象,并且需要将casted
更改为适当的type
。如果我serialize
和array of String
,我得到array of Objects
或Array of Strings
。我在下面试过。在一般情况下,String[] arr = (String[]) objArr;
失败。 但Serialization
后,当我投返回从readObject()
到String[]
,我没有得到任何Exception
。那么返回的是什么? readObject()的方法签名是 public final Object readObject() throws IOException, ClassNotFoundException
它指示它返回Object。 为什么将它转换为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));
}
}
因为实例投射到他们是公民的人类相同的类型。 –