Java: How to force Annotation on Class? [duplicate

2019-03-22 02:15发布

问题:

This question already has an answer here:

  • How do I force a Java subclass to define an Annotation? 3 answers

I have one abstract Class:

public abstract class AbstractItem

and several concrete Classes:

public class ConcreteItem1 extends AbstractItem
public class ConcreteItem2 extends AbstractItem
public class ConcreteItem3 extends AbstractItem

also i have a custom Annotation:

@Target(value = ElementType.TYPE)
@Retention(value = RetentionPolicy.RUNTIME)
public @interface MyAnnotation

How can i force my ConcreteItems to use the MyAnnotation? Can i define that somehow in the AbstractItem-Class?

回答1:

Yes:

Put @Inherited on top of MyAnnotation

@Target(value = ElementType.TYPE)
@Retention(value = RetentionPolicy.RUNTIME)
@Inherited
public @interface MyAnnotation

@MyAnnotation
public abstract class AbstractItem