Finding serialVersionUID of serialized object

Question: Is there a way to determine the generated serialVersionUID of a serialized Java object?

The problem is that I serialized an object without explicitely specifying the serialVersionUID . Now the deserialization process complains about class incompatibilities. However I didn't change the class in a way which would make it incompatible. So I assume that it is enough to specify the serialVersionUID serialVersionUID in the class as it is stored in the object data. In order to do this I need to read the from the serialized data.


Answer:


1)

You can do this by extending ObjectInputStream :

public class PrintUIDs extends ObjectInputStream { 
 
  public PrintUIDs(InputStream in) throws IOException { 
    super(in); 
  } 
 
  @Override 
  protected ObjectStreamClass readClassDescriptor() throws IOException, 
      ClassNotFoundException { 
    ObjectStreamClass descriptor = super.readClassDescriptor(); 
    System.out.println("name=" + descriptor.getName()); 
    System.out.println("serialVersionUID=" + descriptor.getSerialVersionUID()); 
    return descriptor; 
  } 
 
  public static void main(String[] args) throws IOException, 
      ClassNotFoundException { 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    ObjectOutputStream oos = new ObjectOutputStream(baos); 
    List<Object> list = Arrays.asList((Object) new Date(), UUID.randomUUID()); 
    oos.writeObject(list); 
    oos.close(); 
    InputStream in = new ByteArrayInputStream(baos.toByteArray()); 
    ObjectInputStream ois = new PrintUIDs(in); 
    ois.readObject(); 
  } 
 
} 
 

 

I believe it would be possible to read all the serialized data by replacing the descriptor returned by the method, but I haven't tried it.


2)

There is metadata associated with the serialized bits (a header if you like). You can read the value from the metadata if you know at which position it is (the SerialVersionUID is written there along with other info such as the class name).

I think this article might help you: The Java serialization algorithm revealed .

Note that the bits are written "in clear" (unless you encrypted the stream explicitly) so a HEX editor might be all you need to see what is the SerialVersionUID .



This article originates from http://stackoverflow.com/questions/1321988/finding-serialversionuid-of-serialized-object

你可能感兴趣的:(Finding serialVersionUID of serialized object)