Inheriting class annotations

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-30 03:50:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!