gpt4 book ai didi

java - 使用序列化将 Object[] 数组转换为 String[]

转载 作者:行者123 更新时间:2023-12-01 18:35:48 26 4
gpt4 key购买 nike

ObjectInputStreamreadObject() 方法返回对象,需要将其转换为适当的类型 。如果我序列化一个字符串数组,我会得到对象数组还是字符串数组。我在下面尝试过这个。 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com