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中有没有类似注解继承的东西?


- Java包名称中单词分隔符的约定是什么? 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01