Abstract constant in java

Julien Maret :

I would like to create a constant not implemented in super class in order to force subclasses to implement it. The best solution that I've found (on this topic) is to create an abstract method that will return the constant value. I assume that it is impossible to do something like:

abstract final static String Name;

But I still have hope because Java uses something like this in Serializable interface with the serialVersionUID. Did someone know how did they do this? Is it possible to reproduce it in my own class?

Karol Dowbecki :

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;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=35530&siteId=1