Effective Java 37 Use marker interfaces to define types

本文探讨了标记接口和标记注解的区别与应用场景。标记接口用于定义实现了该接口的对象具有的特性,而标记注解则可以为程序元素添加元数据。文章详细分析了两者之间的差异,并提供了选择使用标记接口还是标记注解的指导建议。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

转载于:https://www.cnblogs.com/haokaibo/p/Use-marker-interfaces-to-define-types.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值