I have a question because I'm getting a little confused (or maybe I'm not noticing something obvious). Let's say that I've got some source code that contains a lot of classes which contain a great number of static fields defined like this one:
public final class ConverterTYPE {
private final static HashMap<String, Byte> STRING_MAP = new HashMap<String, Byte>() {
{
put("A", new Byte((byte)12));
put("B", new Byte((byte)13));
}
};
}
As we all know, static fields are not going to be serialized.
However, Java (and Eclipse) complains that "The serializable class does not declare a static final serialVersionUID field of type long". Why can't they notice that static is not going to be serialized?
And the next question: would it be a right solution to this issue to use @SuppressWarnings("serial")
to get rid of all such warnings?
EDIT:
None of my classes implements Serializable interface (or none of their superclasses). And Eclipse is pointing at HashMap<String, Byte>
with its warnings. Why doesn't it detect that it's static field?
Just because that field may not be serialized doesn't mean the thing it references will never itself be serialized! Someone/thing else could get a reference to that map and try to serialize it directly, or use it as an instance member in a serializable class, etc.I see it is private, but making sure it will never be accessed outside the current class or set to an instance member is beyond the scope of the compiler (and impossible with reflection around anyway).
One possible solution is to simply avoid that anonymous subclass w/ initializer style all together and do this:
private final static HashMap<String, Byte> STRING_MAP = new HashMap<String, Byte>();
static {
STRING_MAP.put("A", new Byte((byte)12));
STRING_MAP.put("B", new Byte((byte)13));
}
The result is close to identical in most cases and your code isn't peppered with anonymous classes.