Xavier DSouza Xavier DSouza - 6 months ago 23
Java Question

Marker Interfaces in Java?

I was being taught that Marker interface in Java is an empty interface and is used to signal to compiler or JVM that the objects of the class implementing this interface must be treated in a special way, like serializing, cloning, etc.

But lately I have learned that it actually has nothing to do with the compiler or the JVM. For example, in case of

Serializable
interface the method
writeObject(Object)
of
ObjectOutputStream
does something like
instanceOf Serializable
to detect whether the class implements
Serializable
& throws
NotSerializableException
accordingly.
Everything is handled in the code and this seems to be a design-pattern so I think we can define our own marker interfaces.

Now my doubts:


  1. Is the definition of a marker interface mentioned above in 1st point wrong? How can we define a Marker interface then?

  2. And instead of using the
    instanceOf
    operator why can't the method be something like
    writeObject(Serializable)
    so that there is a compile-time type checking rather than runtime?

  3. How are Annotations better than Marker Interfaces?


Answer
  1. Is the definition of a marker interface mentioned above in 1st point wrong? - It is correct in the parts that (1) a marker interface must be empty, and (2) implementing it is meant to imply some special treatment of the implementing class. The part that is incorrect is that it implies that JVM or the compiler would treat the objects of that class differently: you are correct in observing that it is the code of Java class library that treats these objects as cloneable, serializable, etc. It has nothing to do with the compiler or the JVM.
  2. instead of using the instanceOf operator why can't the method be something like writeObject(Serializable) so that there is a compile-time type checking - This lets you avoid polluting your code with the name of the marker interface when a "plain Object" is needed. For example, if you make a class that needs to be serializable, and has object members, you would be forced to either do casting or make your objects Serializable at compile time. This is inconvenient, because the interface is devoid of any functionality.
  3. How Annotations are better than Marker Interfaces? - They let you achieve the same purpose of conveying metadata about the class to its consumers without creating a separate type for it. Annotations are more powerful, too, letting programmers pass more sophisticated information to classes that "consume" it.