问题
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 ? */
}
回答1:
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
回答2:
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.
回答3:
Annotations are not inherited. But the framework using the annotation (in this case, EJB3), can choose to navigate through the class hierarchy to see if it exists on a superclass.
Look at the javadoc of this annotation: It has an inherited
property which, precisely, indicates if this annotation should also be applied to subclasses or not.
回答4:
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.
回答5:
When a class is marked with an annotation that is itself annotated with java.lang.annotation.Inherited, you can ask for the annotations that are on the class and the Inherited ones should show up in the results.
ApplicationException is not marked as Inherited. Ah well.
来源:https://stackoverflow.com/questions/7173566/inheriting-class-annotations