This question is not about how to use Serializable
, I already know that. However, I was wondering how implementing Serializable
brings up the following warning:
The serializable class MyClass does not declare a static final serialVersionUID field of type long
Suppose I wanted to write an interface like Serializable
, how would I go about "warning" the programmer implementing my interface to declare a variable? I've tried looking at the source code for Serializable.java
but I couldn't find anything which would result in this behaviour. Is this even possible?
Thanks!

- 17,626
- 12
- 64
- 115

- 2,355
- 3
- 22
- 38
2 Answers
I think the behavior you're looking for would be better implemented using annotations and the annotation processor. The fact that the compiler warns you about not declaring serialVersionUID
is handled by a different mechanism at the compiler level (and therefore, out of the reach of the programmer); it's more of a coding convention enforced by the serialization API than a consequence of implementing the Serializable
interface.
In fact, here you can examine the source code of Serializable
and as you can see, there's nothing special about it for forcing a compiler warning:
/* comments removed for brevity */
package java.io;
public interface Serializable {
}

- 232,561
- 37
- 312
- 386
No, I don't think it is possible with mere Java (maybe with some annotations? not sure about it).
The fact is that the Serializable
interface is not a normal Java interface but more a tagging element, it is used as an interface but it's something special, so it is handled in its own way by the compiler (as its meaning expresses a functionality, like interfaces, which is not transparently implemented in the code by default).

- 131,802
- 30
- 241
- 343
-
2Yes, the Java compiler probably does something special to print that warning. I don't think you can program anything like that yourself in Java. – Michael Jun 01 '12 at 15:38
-
`Serializable` has a lot of built-in magic in the language and compiler that you can't replicate in your average library. – Louis Wasserman Jun 01 '12 at 15:39
-
I think @Jack hits all the good points. Nathan, the question is how bad do you want this? [This](http://stackoverflow.com/q/1752607/845279) post describes a possible solution even though it seems like an awful lot of work. Please let us know if it worked. – user845279 Jun 01 '12 at 16:23
-
The Java compiler does not print that warning. Some IDEs do. – user207421 Jun 01 '12 at 22:30