簡體   English   中英

我可以獲取方法調用的帶注釋參數的值嗎?

[英]Can I get the value of an annotated parameter of a method call?

我想獲取方法調用中使用的帶注釋參數的值:

public class Launch {

  public static void main(String[] args) {
    System.out.println("hello");
    testAnn(15);
  }

  private static void testAnn(@IntRange(minValue = 1,maxValue = 10)int babyAge) {
    System.out.println("babyAge is :"+babyAge);
  }
}

我正在嘗試創建一個自定義注釋來驗證 integer 值范圍,該注釋采用minmax ,因此如果有人使用此范圍之外的 integer 值調用此 function,則會出現一條消息錯誤,並提供一些提示出錯了。

我在 Java 注釋過程中工作以獲取值並將其與@IntRange中包含的max/min進行比較

這就是我得到的:

 @Override
 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    for(TypeElement annotaion: annotations) {
        Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(IntRange.class);
        for (Element element : annotatedElements) {

            Executable methodElement= (Executable) element.asType();
            ExecutableType methodExcutableType = (ExecutableType) element.asType();
            String elementParamClassName = methodElement.getParameterTypes()[0].getCanonicalName();
            if(!elementParamClassName.equals(PARAM_TYPE_NAME)) {
                messager.printMessage(Diagnostic.Kind.ERROR,"Parameter type should be int not "+elementParamClassName);
            }else {
                IntRange rangeAnno = element.getAnnotation(IntRange.class);
                int maxValue = rangeAnno.maxValue();
                int minValue = rangeAnno.minValue();
                //code to retrive argument passed to the function with
                //annotated parameter (@IntRange(..))

            }
        }
    }
    return true;
}

您不能使用 Java 注釋處理,因為它僅在編譯時起作用,因此您將能夠獲取@IntRange注釋提供的值,但不能獲取方法參數的當前值。 更多信息在這里

您真正需要的是自定義驗證器,您可以在此處找到如何操作

暫無
暫無

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

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