gpt4 book ai didi

java - java可序列化对象可以在不同的类加载器之间传递吗?

转载 作者:行者123 更新时间:2023-12-02 04:23:22 24 4
gpt4 key购买 nike

最近在学习java程序语言,对java的序列化很好奇,也有一点疑惑。

Can java serializable objects pass between different classloaders? What's the theory?

最佳答案

仅通过实现 Serialized 接口(interface)将不允许您“在不同的类加载器之间传递”。您需要编写代码将序列化对象持久保存到磁盘,然后在另一个类加载器(进程)上将其反序列化。这是一个例子,取自http://www.javapractices.com/topic/TopicAction.do?Id=57 :

    Car car = new Car();
....

//serialize an object called it car to a file called car.ser.
try (
OutputStream file = new FileOutputStream("car.ser");
OutputStream buffer = new BufferedOutputStream(file);
ObjectOutput output = new ObjectOutputStream(buffer);
){
output.writeObject(car); // this call writes file to disk
}
catch(IOException ex){
logger.log(Level.SEVERE, "Cannot perform output.", ex);
}

要反序列化另一端/类加载器/jvm 进程上的对象,您可以执行以下操作:

 try(
InputStream file = new FileInputStream("car.ser");
InputStream buffer = new BufferedInputStream(file);
ObjectInput input = new ObjectInputStream (buffer);
){
//deserialize the List
Car car = (Car)input.readObject();
//display its data
System.out.println("Recovered Car: " + car);

}
catch(ClassNotFoundException ex){
logger.log(Level.SEVERE, "Cannot perform input. Class not found.", ex);
}
catch(IOException ex){
logger.log(Level.SEVERE, "Cannot perform input.", ex);
}

编辑:为了获取序列化文件并反序列化它们,您可以使用 WatchService

关于java - java可序列化对象可以在不同的类加载器之间传递吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32492877/

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