問題描述
我正在探索注解并發現一些注解似乎在它們之間具有層次結構.
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中有沒有類似注解繼承的東西?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!