gpt4 book ai didi

java - 标记注释与标记接口(interface)

转载 作者:行者123 更新时间:2023-12-02 06:13:30 24 4
gpt4 key购买 nike

在阅读有关标记接口(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 - 标记注释与标记接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55890850/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com