我可以获取方法调用的带注释的参数的值吗?

问题描述

我想获取方法调用中使用的带注释的参数的值:

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);
  }
}

我正在尝试创建一个自定义批注以验证整数值范围,该批注采用minmax值,因此,如果有人使用此范围之外的整数值调用函数,将会出现一条消息错误,并带有一些提示,指出发生了什么问题。

我正在使用Java注释过程来获取值并将其与max/min中包含的@IntRange进行比较

这就是我得到的:

 @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注释的值,但不能获得当前方法之一参数。更多信息here

您真正需要的是自定义验证器,您可以找到如何进行here