简体   繁体   中英

Is there a way to make a specific Java annotation mandatory in subclasses of a specific class

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM