1

How does the java compiler warn you about not declaring a serialVersionUID uid field? Is there a way I can do that for a custom interface or is that java language magic?

Edit:

My question isn't so much about the serializable interface, I understand that. But how does it generate the warning? I want to implement the same thing (warn if classes implementing my interface don't provide a certain attribute) but I don't see anything on how serializable does it.

Falmarri
  • 47,727
  • 41
  • 151
  • 191

3 Answers3

2

It won't warn you, it will just generate serialVersionUID for you silently. Most IDEs however will trigger warnings for Serializable classes without this field (for a reason).

See also: Use the serialVersionUID or suppress warnings?

Community
  • 1
  • 1
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
1

I'm not quite sure what your asking. It's a feature of the Serializable interface, I think combined with Eclipse's code style options (or whatever IDE you're using), that generates this warning. If you check under code style options (which generally give you a number of warning you an turn on, so the IDE can help you keep your code clean), I think you'll find the option that generates this warning.

The purpose of the warning, in case you're wondering, is that the serialVersionUID is used to uniquely identify a serialized object. When your code tries to de-serialize that object (say, from a file), if you're using the standard serialization techniques in Java, the JVM will throw an error when the serialVerionUID for the class you're trying to de-serialize, doesn't match the one in the complied class file. It one way of the JVM loading a serialized object that contains a previous/alternate version of the given object/data structure.

jefflunt
  • 33,527
  • 7
  • 88
  • 126
1

As the other answers say, the warning you are looking for is highly specific to Serializable.

In general, an interface cannot specify what fields should exist in classes that implement it. This is actually basic OO design - a field is implementation, not interface.

For your need, perhaps it would be better to have a method in the interface, getTheField(). Classes implementing the interface would then be required to implement that method. They may or may not do so by using a private field to store the data, but that seems like an internal implementation detail that should not matter to the callers.

Dave Costa
  • 47,262
  • 8
  • 56
  • 72