3

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?

4

2 回答 2

6

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.

于 2012-02-19T14:15:06.740 回答
2

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.

于 2012-02-19T15:02:07.560 回答