簡體   English   中英

如何強制 Java 子類定義注釋?

[英]How do I force a Java subclass to define an Annotation?

如果一個類定義了一個注解,是否有可能以某種方式強制其子類定義相同的注解?

例如,我們有一個簡單的類/子類對,它們共享@Author @interface. 我想要做的是強制每個進一步的子類定義相同的@Author注釋,防止在某個地方出現RuntimeException

測試類.java:

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@interface Author { String name(); }

@Author( name = "foo" )
public abstract class TestClass
{
    public static String getInfo( Class<? extends TestClass> c )
    {
        return c.getAnnotation( Author.class ).name();
    }

    public static void main( String[] args )
    {
        System.out.println( "The test class was written by "
                        + getInfo( TestClass.class ) );
        System.out.println( "The test subclass was written by " 
                        + getInfo( TestSubClass.class ) );
    }
}

測試子類.java:

@Author( name = "bar" )
public abstract class TestSubClass extends TestClass {}

我知道我可以在運行時枚舉所有注釋並檢查缺少的@Author ,但如果可能的@Author ,我真的很想在編譯時這樣做。

您可以在編譯時使用 JSR 269 做到這一點。 見: http : //today.java.net/pub/a/today/2006/06/29/validate-java-ee-annotations-with-annotation-processors.html#pluggable-annotation-processing-api

編輯 2020-09-20:鏈接已死,存檔版本在這里: https ://web.archive.org/web/20150516080739/http://today.java.net/pub/a/today/2006/06/29 /validate-java-ee-annotations-with-annotation-processors.html

我很確定這在編譯時是不可能做到的。

然而,這對於“單元”測試來說顯然是一項任務。 如果您有這樣的約定想要強制執行,但很難或不可能用編譯器檢查,“單元”測試是檢查它們的簡單方法。

另一種可能性是在靜態分析器中實現自定義規則。 這里也有很多選擇。

(我將單元放在引號中,因為這實際上是對約定的測試,而不是特定單元的測試。但它應該與您的單元測試一起運行)。

您可以在超類上使用 @Inherited 制作注釋(例如 @EnforceAuthor),並使用編譯器注釋(自 Java 1.6 起)在編譯時趕上。 然后你有一個對子類的引用,並且可以檢查是否缺少另一個注釋(例如@Author)。 這將允許取消編譯並顯示錯誤消息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM