Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheriting class annotations

Is there a way to make classes inherit annotations from a superclass ?

e.g.

@ApplicationException(rollback=true)
public abstract class AbstractBeanActionException extends Exception {
    /* method body is simply calls to super() */
}

public class OrderBeanException extends AbstractBeanActionException {
    /* does this class have to be annotated as well ? */
}
like image 904
Luke Avatar asked Aug 24 '11 09:08

Luke


People also ask

Are class annotations inherited?

Class annotations can not be inherited by subclasses, but annotations on nonprivate non-constructor member methods and fields are inherited, together with the method / field they are associated with. So you may try using these to achieve the desired effect.

What is the use of inherited annotation?

The @inherited in Java is an annotation used to mark an annotation to be inherited to subclasses of the annotated class. The @inherited is a built-in annotation, as we know that annotations are like a tag that represents metadata which gives the additional information to the compiler.

Are Spring annotations inherited?

Annotations on methods are not inherited by default, so we need to handle this explicitly.

What is @interface annotation in Java?

@interface is used to create your own (custom) Java annotations. Annotations are defined in their own file, just like a Java class or interface. Here is custom Java annotation example: @interface MyAnnotation { String value(); String name(); int age(); String[] newNames(); }


2 Answers

If you define your annotations classes yourself, then you can use @Inherited meta annotation:

Indicates that an annotation type is automatically inherited. If an Inherited meta-annotation is present on an annotation type declaration, and the user queries the annotation type on a class declaration, and the class declaration has no annotation for this type, then the class's superclass will automatically be queried for the annotation type.

like image 130
Andrey Adamovich Avatar answered Sep 19 '22 09:09

Andrey Adamovich


Class annotations can not be inherited by subclasses.

What you can do is "force" the subclass to use the annotation at compile time:

https://community.oracle.com/docs/DOC-983563

like image 23
Luciano Fiandesio Avatar answered Sep 21 '22 09:09

Luciano Fiandesio