If I serialize a Class object (for example, HashMap.class ) and then deserialize it in another JVM instance, it turns out that the deserialized class is identical to the one currently loaded:
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.HashMap; final class DeserializationTest { static String path = "/home/suseika/test.ser"; static Class<HashMap> cls = HashMap.class; public static void main(String[] args) throws Exception { if (args[0].equals("serialize")) { serialize(); } else if (args[0].equals("deserialize")) { final Object deserialized = deserialize();
How can Java deserialize objects in this case to maintain identity? Class does not seem to implement writeObject() / readObject() / readResolve() .
Can this behavior be violated when loading a certain class / using a specific class loader / using a specific JVM installation / do something during serialization? Are there cases where a loaded Class will not be the same as a deserialized one? In other words, can I rely on this behavior in my application to serialize and deserialize Class objects?
source share