java中有没有类似注解继承的东西? [英] Is there something like Annotation Inheritance in java?

查看:24
本文介绍了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中有没有类似注解继承的东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆