What is the purpose of marker interface? [duplicate]
Possible Duplicates:
marker interface What is the purpose of a marker interface?
I know what is marker interface - An interface with no methods. Example: Serializable, Remote, Cloneable.
I am wondering what is the purpose of marker inteface. This is my understanding:-
Basically it is just to identify the special objects from normal objects. Like in case of serialization , objects that need to be serialized must implement serializable interface and down the line writeObject() method must be checking somewhere if it is a instance of serializable or not. As far as i think ,Thats the only purpose for which writeObject using interface serializable(marker interface). Right? or jvm provides some extra functionality too on the basis of serializable interface?
开发者_如何学编程Similar kind of logic is true for cloneable interface.
Now lets see how it is useful.
Lets say in a application we have 1000 value objects.We want to serialize only 100 specific objects . Now JDK has said that programmer role is just to mark the object as special with marker interface in this case its serializable interface.Now JDK will take care of that which object to serialize or not?
Yes we could achieve this kind of behaviour with some kind of bollean flag . but that would be a bad approach.
Similarily we can say in case of user defined marker interface , we can distinguish special objects with help of marker interface.Like we can use instance of operator to determine if it is a instance of that particular interface . If yes proceed in case of No throw some exception.
Please let if above understanding is correct?
Your understanding is correct. The marker interface also defines a type. It can thus be used in method signatures. For example, Hibernate's Session.get() method takes a Serializable as argument. It avoids passing a primary key that would not be serializable as argument.
Note that Cloneable is, retrospectively, seen as a bad design choice.
Serializable could certainly have been implemented with an annotation if those had existed when serialization was implemented.
Marker interfaces are, most of the time, an anti-pattern. An interface should define a polymorphic behaviour. A marker interface can be replaced by an annotation.
精彩评论