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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With