Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous initialization - strange serialization warning [duplicate]

I was wondering why when I use an anonymous instanciation along with an instance initializer block, I get a "serializable class does not declare a static final serialVersionUID field of type long" compile-time warning.

Here's what I mean. Let's say I want to instantiate an ArrayList and at the same time add something to it like so:

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

If I compile this all is ok but I get the serialVersionUID field missing warning. Now ArrayList already implements serializable and has a private static final long serialVersionUID so why is it that when I use it like that it seems that that field "dissapears" and I get a warning for not having it declared?

like image 935
Shivan Dragon Avatar asked Oct 25 '11 19:10

Shivan Dragon


3 Answers

When you create your anonymous class, you are actually extending ArrayList and therefore, inheriting the Serializable interface.

All Serializable classes are supposed to have a serialVersionUID so that you can distinguish between different serialized versions of the classes. Since the anonymous type is a new class, it would be a good idea to give it an ID so you can distinguish between different versions of it.

like image 113
Jack Edmonds Avatar answered Sep 30 '22 23:09

Jack Edmonds


Because you're creating what's essentially a subclass. Such a subclass needs its own serial version UID. Same thing happens when you subclass things like JPanel. It's not a terrible problem if you don't require (de)serialization.

like image 42
G_H Avatar answered Oct 01 '22 00:10

G_H


new ArrayList<Object>() {

    {
        add(new Object());
    }

};

You are not just instantiating but first defining a subclass (anonymous) of ArrayList and then instantiating the subclass.

Even though there is a private static final long serialVersionUID in ArrayList, since it's static, its not inherited by your anonymous subclass. So it's missing that field.

like image 45
Bhesh Gurung Avatar answered Oct 01 '22 00:10

Bhesh Gurung