Recently I learn the java program language.I am curious about the java serializable and have a little doubts about it.
Can java serializable objects pass between different classloaders? What's the theory?
Recently I learn the java program language.I am curious about the java serializable and have a little doubts about it.
Can java serializable objects pass between different classloaders? What's the theory?
Just by implementing the Serializable interface won't allow you to "pass between different classloaders" . You need to write code to persist the serialized object to disk, and then on the other classloader (process) deserialize it. here's an example, taken from 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);
}
To deserialize the object on the other end/classloader/jvm process you can do this:
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);
}
EDIT: In order to pickup serialized files and deserialize them, you can use a WatchService
A "serializable object" can't, but you can serialize the object, and save the data anywhere. At some future point, on the same machine or a different one, in the same VM or a different one, in the same classloader or a different one, you can deserialize the saved data back into an object.