Abstract constant in java

serialVersionUID field presence is not enforced by the Serializable interface because interface can't enforce presence of a field. You can declare a class which implements Serializable, it will compile just fine without serialVersionUID field being there.

The check for serialVersionUID field is hardcoded in the tools. One example is JDK java.io.ObjectStreamClass.getSerialVersionUID() methods that loads the serialVersionUID value with reflection:

/**
 * Returns explicit serial version UID value declared by given class, or
 * null if none.
 */
private static Long getDeclaredSUID(Class<?> cl) {
    try {
        Field f = cl.getDeclaredField("serialVersionUID");
        int mask = Modifier.STATIC | Modifier.FINAL;
        if ((f.getModifiers() & mask) == mask) {
            f.setAccessible(true);
            return Long.valueOf(f.getLong(null));
        }
    } catch (Exception ex) {
    }
    return null;
}

Such constant cannot be static because static fields are shared among all instances of the class, including instances of all subclasses. Here is how to implement this as non-static constant:

public abstract class Foo {
  public final String name; // Particular value to be defined in subclass

  protected Foo (String name) {
    this.name = name;
  }
}

public class Bar extends Foo {
  public Bar () {
    super ("Zoo"); // Here we define particular value for the constant
  }
}

BTW, serialVersionUID is not a part of Serializable interface.


When a class implementing Serializable does not have a serialVersionUID the little message you see in your IDE and while compiling is a warning emitted by javac. If you want to create something like that you can but the process seems complicated. The solution is here in this answer.

They go into detail but the general idea is to create an annotation and annotation processor and use the annotation processor during compilation. I'm guessing you could use reflection (or... not reflection since it is compile time?) to see if the annotated class contains the field you want.


I wouldn't recommend it but if you need it so much you could create a regex check in Checkstyle and force people to implement the static variable

Tags:

Java