Adam Matan
Adam Matan

Reputation: 136181

Java Double brace initialization

I have refactored the following object initialization:

Req r = new Req();
r.set_f1("A");
r.set_f2(123);
r.set_f3(123.456);

Into:

Req r = new Req() {{
    set_f1("A");
    set_f2(123);
    set_f3(123.456)
}};

The second sample raises the following Eclipse warning:

The serializable class does not declare a static final serialVersionUID field of type long

I thought that these code samples should be equivalent - what's the difference?

Upvotes: 3

Views: 514

Answers (2)

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147154

If the base class implements java.io.Serializable then subclasses will should have a serialVersionUID. Inner classes should not be serialisable.

If you are planning objects created by this code to be exposed to other code that potentially might want to serialise the data, don't use the double brace idiom (I suppose you could use it with writeReplace, but that gets a bit ugly). If you are sure your code isn't going to come into contact with serilisation, stick @SuppressWarnings("serial") on the widest possible context.

Upvotes: 2

Irfy
Irfy

Reputation: 9587

The second one creates an anonymous subclass and initializes it with an unnamed initializer. If the Req is serializable, any subclass of it is, and should hence define a serialVersionUID.

Upvotes: 6

Related Questions