Search code examples
javaserializationserialversionuid

Finding serialVersionUID of serialized object


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 in the class as it is stored in the object data. In order to do this I need to read the serialVersionUID from the serialized data.


Solution

  • 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.