Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the need of marker interface when Attributes serve the purpose?

Tags:

c#

.net

I'm a bit confused about

The purpose of Marker Interface Vs Attributes.

Their purpose looks same to me(Pardon me if I'm wrong).

Can anyone please explain how do they differ in purpose?

like image 289
Manish Avatar asked Oct 13 '10 12:10

Manish


People also ask

What is the purpose of a marker interface?

A marker interface is an interface that has no methods or constants inside it. It provides run-time type information about objects, so the compiler and JVM have additional information about the object. A marker interface is also called a tagging interface.

What is advantage of annotations over marker interface?

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.

What is a marker interface give an example?

It is an empty interface (no field or methods). Examples of marker interface are Serializable, Cloneable and Remote interface. All these interfaces are empty interfaces.

What can we use instead of marker interface?

In modern Java, marker interfaces have no place. They can be completely replaced by Annotations, which allow for a very flexible metadata capability. If you have information about a class, and that information never changes, then annotations are a very useful way to represent it.


1 Answers

Here are some advantages of both.

Marker interfaces:

  • are a bit easier to check for using dynamic type checks (´obj is IMarker´);
  • allow for functional and data extensibility in the future (i.e. turning a “marker” interface into a “full” interface that actually declares some members);
  • can be used in generic type constraints;

On the other hand, attributes:

  • provide a clearer separation of metadata;
  • allow for specifying additional information via their constructors or properties;
  • allow for multiple application to an entity;
  • are general-purpose in terms of applicability to different kinds of entities, not just classes;

It heavily depends on the particular application's architecture and design whether it's appropriate to use a marker interface or an attribute in a particular case.

like image 57
Ondrej Tucny Avatar answered Sep 19 '22 05:09

Ondrej Tucny