簡體   English   中英

Java中的注釋(參數)驗證?

[英]Annotation (parameter) validation in Java?

有什么方法可以驗證Java中的注釋有效性?

例如我可能有一個注釋

public @interface Foo {
   int number();
   String name();
}

public @interface Foos {
    Foo[] value();
    /* Foos() {
        for(int i=0; i<value().length; ++i) {
            if( i != value()[i].number() ) {
                throw new IllegalArgumentException();
            }
        }
    } */
}

我可以限制numbers從零開始並連續嗎?

(在上面的示例中,我編寫了此簽入注釋的注釋構造函數)

更新

注釋用法的一些示例:

// correctly annotated class
@Foos({@Foo(number=0, name="first"), @Foo(number=1,name="second")})
class MyCorrectAnnotatedClass {
}

// incorrectly annotated class 1
// number starts from 1 not form 0
@Foos({@Foo(number=1, name="first"), @Foo(number=2,name="second")})
class MyIncorrectAnnotatedClass1 {
}

// incorrectly annotated class 2
// number sequence has missed 1
@Foos({@Foo(number=0, name="first"), @Foo(number=2,name="second")})
class MyIncorrectAnnotatedClass2 {
}

您是說要檢查所有使用注解的地方,以便每個數字從0開始僅使用一次嗎? 這不可能以簡單的方式實現。

如果確實要執行此操作,則必須編寫代碼以掃描類路徑上的所有類,找到使用注釋的所有類,然后檢查注釋的值。 (如果注釋用於方法或其他方法而不是類上,則更加困難)。

您不能將實現代碼(例如構造函數)添加到注釋中。 這樣,注釋類似於接口。

暫無
暫無

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

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