As marker interfaces are mostly useful for just marking a class, the same thing can be achievable through annotations. For example Cloneable
interface can be @Cloneable
.
So is there still need for marker interfaces or can be relpaced by Annotations? Is there any advantage/disadvantage of using any of them? I mean prefer one over other?
Instead of marker interface, Java 5 provides the annotations to achieve the same results. It allows flexible metadata capability. Therefore, by applying annotations to any class, we can perform specific action.
It seems annotation is a better choice than the marker interface as the same effect can be achieved by the annotations. It can mark variables, methods, and/or classes. It can mark any class specifically, or via inheritance. A marker interface will mark all subclasses of the marked class.
In Java, an annotation type is a form of an interface, so you can implement it and use an instance.
Hence, the correct answer is option (a). 28) Which of the following is a marker interface? Explanation: A marker interface is an interface with no fields and methods. In other words, an empty interface (contains nothing) is known as the marker interface.
Marker interfaces are better than annotations when they're used to define a type. For example, Serializable can be used (and should be used) as the type of an argument that must be serializable. An annotation doesn't allow doing that:
public void writeToFile(Serializable object);
If the marker interface doesn't define a type, but only meta-data, then an annotation is better.
One more thing to mention would be the cost of using annotations. To check if object is an instance of an interface one can use instanceof
which is a relatively low-cost operation nowadays. Using annotations requires Java reflection
calls and is far more costly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With