Alex Rivera | Logout

Understanding this warning: The serializable class does not declare a static final serialVersionUID

Asked 2009-10-03T21:14:49.620
25

I have some static initializer code:

someMethodThatTakesAHashMap(new HashMap<K, V>() {
{
  put("a","value-a"); 
  put("c","value-c");}
});

For some reason I am receiving a warning from Eclipse: The serializable class does not declare a static final serialVersionUID.

Is this complaining about the anonymous class? What can I do about that, or should I just suppress it.

Edit
Report

1 Answer

30

The syntax you're using is called double-brace initialization - which is actually an "instance initialization block that is part of an anonymous inner class" (certainly not a hack). So, when using this notation, you are actually defining a new class(!).

The "problem" in your case is that HashMap implements Serializable. This interface doesn't have any methods and serves only to identify the semantics of being serializable. In other words, it's a marker interface and you concretely don't have to implement anything. But, during deserialization, Java uses a version number called a serialVersionUID to verify that the serialized version is compatible with the target. If you don't provide this serialVersionUID, it will be calculated. And, as documented in the javadoc of Serializable, the calculated value is extremely sensitive and it is thus recommended be explicitly declare it to avoid any deserialization problems. And this is what Eclipse is "complaining" about (note that this is just a warning).

So, to avoid this warning, you could add a serialVersionUID to your annonymous inner class:

someMethodThatTakesAHashMap(new HashMap<String, String>() {
    private static final long serialVersionUID = -1113582265865921787L;

    {
        put("a", "value-a");
        put("c", "value
answered 2010-01-26T03:27:06.247

Your Answer