Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can annotations totally replace Marker Interfaces?

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?

like image 598
Narendra Pathai Avatar asked Mar 04 '13 11:03

Narendra Pathai


People also ask

What can we use instead of marker interface?

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.

Are marker interfaces better than annotations?

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.

Can an annotation implement an interface?

In Java, an annotation type is a form of an interface, so you can implement it and use an instance.

Which of the following is correct about marker interface?

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.


2 Answers

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.

like image 138
JB Nizet Avatar answered Nov 07 '22 00:11

JB Nizet


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.

like image 24
Dariusz Avatar answered Nov 06 '22 23:11

Dariusz