簡體   English   中英

如何在Java中獲取帶注釋的值?

[英]How can I get the annotated value in java?

我正在嘗試@Pattern批注以驗證輸入

    @Pattern(regexp="[A-Za-z0-9_.]*", message="Name can only contain alphanumeric characters and underscores and dots")
    public String getName() {
        return name;
    }

我還希望錯誤message包含所傳遞name的實際值。 如何在注釋調用中訪問它? 例如,我想要類似的東西:

    @Pattern(regexp="[A-Za-z0-9_.]*", message="Name can only contain alphanumeric characters and underscores and dots. Provided name: " + name + " is not valid")

我嘗試了此操作,並收到一條錯誤消息,指出The value for annotation attribute Pattern.message must be a constant expression 有什么辦法可以在注釋定義(具體是錯誤消息)中獲取實際的變量值? 我想通過顯示實際提供的值使錯誤消息更有用。

您可能需要一個自定義約束來覆蓋@Pattern生成的默認錯誤消息。 此處查看相關文檔。

暫無
暫無

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

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