Is there something like Annotation Inheritance in java?(java中有没有类似注解继承的东西?)
问题描述
我正在探索注解并发现一些注解似乎在它们之间具有层次结构.
I'm exploring annotations and came to a point where some annotations seems to have a hierarchy among them.
我正在使用注释在后台为卡片生成代码.有不同的卡片类型(因此不同的代码和注释),但它们之间有一些共同的元素,如名称.
I'm using annotations to generate code in the background for Cards. There are different Card types (thus different code and annotations) but there are certain elements that are common among them like a name.
@Target(value = {ElementType.TYPE})
public @interface Move extends Page{
String method1();
String method2();
}
这将是常见的注释:
@Target(value = {ElementType.TYPE})
public @interface Page{
String method3();
}
在上面的示例中,我希望 Move 继承方法 3,但我收到一条警告,指出扩展对注释无效.我试图让一个注释扩展一个公共基础,但这不起作用.这甚至可能还是只是一个设计问题?
In the example above I would expect Move to inherit method3 but I get a warning saying that extends is not valid with annotations. I was trying to have an Annotation extends a common base one but that doesn't work. Is that even possible or is just a design issue?
推荐答案
很遗憾,没有.显然,它与读取类上的注释而不一直加载它们的程序有关.请参阅 为什么不能在 Java 中扩展注释?一个>
Unfortunately, no. Apparently it has something to do with programs that read the annotations on a class without loading them all the way. See Why is it not possible to extend annotations in Java?
但是,如果这些注解是 @Inherited
.
However, types do inherit the annotations of their superclass if those annotations are @Inherited
.
此外,除非您需要这些方法进行交互,否则您可以将注释堆叠在您的类上:
Also, unless you need those methods to interact, you could just stack the annotations on your class:
@Move
@Page
public class myAwesomeClass {}
有什么不适合你的原因吗?
Is there some reason that wouldn't work for you?
这篇关于java中有没有类似注解继承的东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:java中有没有类似注解继承的东西?


基础教程推荐
- 从 python 访问 JVM 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 大摇大摆的枚举 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01