Search code examples
javaserializationserialversionuid

How to generate serialVersionUID for anonymous class?


This is what I tried:

I built the project with the -Xlint:serial option, and I got this warning:

MyClass.java:42: warning: [serial] serializable class <anonymous mypackage.MyClass$1> has no definition of serialVersionUID
        SerializableClass myObject = new SerializableClass() {
1 warning

Then copied the anonymous class name as parameter for serialver:

>serialver -classpath dist\Example.jar mypackage.MyClass$1

mypackage.MyClass$1:    static final long serialVersionUID = 23L;

I'm not going to serialize it, and I've read that it is not recommended to serialize objects of anonymous classes.

Is it a better practice to leave it as 1L, or to have no definition of serialVersionUID at all?


Solution

  • I would recommend omitting serialVersionUID and if you want to compile warnings-free, to add @SuppressWarnings("serial") at the declaration of myObject.

    The reason is that serialVersionUID is a mechanism for maintaining serial compatibility across versions, and since you never serialize the object, serial compatibility doesn't matter.

    In addition, serializing anonymous inner classes is problematic for several reasons. The generated class name, which is part of the serial format, is compiler-specific, and it may change uncontrollably if the rest of the file is modified and recompiled. Anonymous inner classes also contain hidden fields for the enclosing instance and for captured locals, which will also be included in the serialized form -- if they're serializable at all.