【问题标题】:Can I get the value of an annotated parameter of a method call?我可以获取方法调用的注释参数的值吗?
【发布时间】:2020-09-20 13:08:11
【问题描述】:

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

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 注释流程来获取值并将其与 @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 validation annotations annotation-processing


    【解决方案1】:

    您不能使用 Java 注释处理,因为它仅在编译时工作,因此您将能够获取 @IntRange 注释的提供值,但不能获取方法参数的当前值。更多信息here

    你真正需要的是一个自定义验证器,你可以找到如何做到这一点here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-17
      • 1970-01-01
      • 2022-01-25
      相关资源
      最近更新 更多