ObjectInputStream
的 readObject()
方法返回对象,需要将其转换
为适当的类型
。如果我序列化
一个字符串数组
,我会得到对象数组
还是字符串数组
。我在下面尝试过这个。 String[] arr = (String[]) objArr;
在一般情况下失败。
但是在序列化
之后,当我将从readObject()
返回的Object
转换为String[]
时,我不获取任何异常
。那么返回的是什么?
readObject() 的方法签名是
public final Object readObject() 抛出 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));
}
}
最佳答案
在第一个示例中,您创建一个 Object[]
类型的对象,并将其转换为 String[]
。由于 Object[]
不扩展 String[]
,因此转换失败。这就像想把香蕉扔给苹果一样。香蕉不是苹果,所以转换失败。
在序列化示例中,String[]
类型的对象被序列化,然后反序列化。序列化机制包括写入对象的类型,然后写入其状态。反序列化时,它会重新创建相同类型的对象 (String[]
),然后用读取的状态填充它。因此,该对象是一个 String[]
,并且将 String[]
转换为 String[]
效果很好。
关于java - 使用序列化将 Object[] 数组转换为 String[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22082451/