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
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.