java - 标记注释与标记界面

标签 java interface annotations

在阅读有关标记接口(interface)的内容时,我偶然发现了以下站点:Item 37: Use marker interfaces to define types
在这里,根据 Joshua Bloch 的说法,与 Marker 注释相比,Marker 接口(interface)有两个优势。

  1. Marker interfaces define a type that is implemented by instances of the marked class; marker annotations do not. The existence of this type allows you to catch errors at compile time that you couldn’t catch until runtime if you used a marker annotation.

  2. Another advantage of marker interfaces over marker annotations is that they can be targeted more precisely. If an annotation type is declared with target ElementType.TYPE, it can be applied to any class or interface. Suppose you have a marker that is applicable only to implementations of a particular interface. If you define it as a marker interface, you can have it extend the sole interface to which it is applicable, guaranteeing that all marked types are also subtypes of the sole interface to which it is applicable.

好的,第一点理解了,但我不确定我是否正确理解了第二点:

If an annotation type is declared with target ElementType.TYPE, it can be applied to any class or interface.

同样,如果我有一个标记接口(interface),那么它也可以应用于任何类或接口(interface)。标记注解和标记接口(interface)不是说的一样吗? 如何更精确地定位标记界面?

第二点也提到:

you can have [the Marker Interface] extend the sole interface to which it is applicable, guaranteeing that all marked types are also subtypes of the sole interface to which it is applicable.

难道您不能通过使用 @Inherited 元注释 也通过注释实现这一点吗?

最佳答案

How can a marker interface be targeted more precisely?

你是对的,两者都可以应用于任何类型。通过“更精确地定位”,作者的意思是您可以添加额外的限制,可以将标记接口(interface)应用于哪些特定类型。不可能对注释添加相同的精确限制:如果注释仅限于 ElementType.TYPE,那么它始终可以应用于所有类型。

第二点的另一部分详细介绍了如何添加这些限制。如果你有一个标记接口(interface),你可以让它扩展另一个接口(interface)(作者称之为唯一接口(interface)),如下所示:

interface Marker extends Foo { }

标记现在只能应用于实现 Foo 的类型。

Can't you also achieve this with annotations, by using the @Inherited meta-annotation?

不,@Inherited 元注解仅意味着注解类的任何子类型都将被视为具有相同的注解。它不会对可以应用注释的类型施加任何限制。

关于java - 标记注释与标记界面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26271786/

相关文章:

Java - 转义 HTML 字符(不包括某些字符)

java - 这在 Java 中的 ArrayList 中是什么意思

java - Derby 嵌入式驱动程序错误 XBM02 请确保您的类路径包含正确的 Derby 软件

function - typescript 接口(interface) : function as property - or - this in interface implementations

java - 如何修改/覆盖从 Groovy 基本脚本继承的变量?

asp.net - 为什么单选按钮列表总是换行?

arrays - 创建一个具有可变长度数组的接口(interface),包含 TypeScript/Angular4 中的对象

java - Java 注释是否添加符号或功能?

android - @UnsupportedAppUsage 注解描述了什么

java - 参数化测试: Collection not read by JUnit?