Anonymous initialization - strange serialization warning

I was wondering why, when I use anonymous instanciation together with the instance initializer block, I get a "serializable class" that does not declare a static final field serialVersionUID of type long "compilation warning.

Here is what I mean. Let's say I want to create an instance of ArrayList and at the same time add something to it like this:

ArrayList<Object> arrayList = new ArrayList<Object>(){{add(new Object());}}; 

If I compile this, everything is fine, but I get the serialVersionUID field without warning. Now ArrayList already implements serializable and has private static final long serialVersionUID , so why, when I use it like that, does this field seem to β€œdisappear” and I get a warning that it is not declared?

+4
source share
3 answers

When you create your anonymous class, you actually extend the ArrayList and therefore inherit the Serializable interface.

All Serializable classes must have serialVersionUID so you can distinguish between different serialized versions of classes. Since the anonymous type is a new class, it would be nice to give it an identifier so that you can distinguish between different versions of it.

+7
source

Because you are creating what is essentially a subclass. Such a subclass must have its own serial version UID. The same thing happens when you subclass things like JPanel. This is not a terrible problem unless you require serialization (de).

+2
source
 new ArrayList<Object>() { { add(new Object()); } }; 

You do not just instantiate, but first define a subclass of (anonymous) ArrayList , and then instantiate the subclass.

Even if ArrayList has a private static final long serialVersionUID , since it is static , your anonymous subclass has not inherited it. Therefore, this field is missing.

0
source

All Articles