Marker Annotation vs Marker Interface

后端 未结 1 1298
情歌与酒
情歌与酒 2020-12-10 11:44

While reading about Marker interfaces I stumbled upon the following site : Item 37: Use marker interfaces to define types
Here, according to Joshua Bloch there are two

1条回答
  •  时光说笑
    2020-12-10 12:07

    How can a marker interface be targeted more precisely?

    You are correct that both could be applied to any type. By "targeted more precisely" the author means that you can add additional restrictions to which specific types a marker interface can be applied to. It is not possible to add the same precise restrictions to annotations: If an annotation is restricted to ElementType.TYPE, then it can always be applied to all types.

    The other part of the 2nd point goes into details how you can add those restrictions. If you have a marker interface, you can let it extend another interface (which the author calls the sole interface) like this:

    interface Marker extends Foo { }
    

    The marker can now only be applied to types which implement Foo.

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

    No, the @Inherited meta-annotation only means that any subtype of an annotated class will be treated as if it also had the same annotation. It does not impose any restrictions to which types the annotation can be applied to.

    0 讨论(0)
提交回复
热议问题