开发者

Inheriting class annotations

Is there a way to make classes inherit an开发者_运维问答notations 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 ? */
}


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.


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


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜