代码改变世界

Effective Java 37 Use marker interfaces to define types

2014-03-31 09:03  小郝(Kaibo Hao)  阅读(556)  评论(0编辑  收藏  举报

Marker interface is an interface that contains no method declarations, but merely designates (or "marks") a class that implements the interface as having some property.

 

Such as Serializable interface which indicates that the instance implements it can be the argument of the method ObjectOutputStream.write(Object) correctly. Or the Set interface which implements Collection interface by just implementing all the methods of Collection without adding new method.

Differences

Marker Interface

Marker annotation

Define a type that is implemented by instances of the marked class

Y

N

It's possible to add more information to an annotation type after it is already in use.

N

Y

Applies to any program element other than a class or interface, as only classes and interfaces can be made to implement or extend an interface.

N

Y

Mark classes and interfaces

Y

N

   

Note

If the marker applies only to classes and interfaces, ask yourself the question, Might I want to write one or more methods that accept only objects that have this marking? If so, you should use a marker interface in preference to an annotation. This will make it possible for you to use the interface as a parameter type for the methods in question, which will result in the very real benefit of compile-time type checking.

   

If you answered no to the first question, ask yourself one more: Do I want to limit the use of this marker to elements of a particular interface, forever? If so, it makes sense to define the marker as a subinterface of that interface. If you answered no to both questions, you should probably use a marker annotation

   

Summary

If you find yourself writing a marker annotation type whose target is ElementType.TYPE, take the time to figure out whether it really should be an annotation type, or whether a marker interface would be more appropriate.