3

I am not a super expert in Java annotations, and I wanted to find out if there is a way to make sure that given a subclass of a specific class, the subclass must use a specific Java annotation on the class definition itself or the code won't compile?

Thanks IS

user1805458
  • 1,081
  • 3
  • 9
  • 21
  • 1
    `@Inherited` helps https://stackoverflow.com/questions/7173566/inheriting-class-annotations – Dan Jul 24 '18 at 18:18

1 Answers1

0

I don't think there is a way to enforce the developer to put annotation on subclass.

However, you can add the required annotations on your parent class and its subclass will "automatically" have the annotation without you explicitly specifying.

@RequiredAnnotations
class Parent{
    //...
}

// it will have @RequiredAnnotations without specifying
class Child extend Parent{
    //...
}

It works with interface, concrete class or abstract class inheritance.

Like Pedro points out, the @RequiredAnnotation needs to have @Inherited to make it work.

Minjun Yu
  • 3,497
  • 4
  • 24
  • 39
  • This is not exactly true. The annotation will only be inherited if it is annotated with "@Inherited". Take for example "@Deprecated" which is not, try calling getAnnotations() on the subclass and you won't find @Deprecated – Pedro Jul 24 '18 at 20:23