简体   繁体   中英

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

I want to get the value of an annotated parameter used in a method invocation:

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

What I'm trying is create a custom annotation to validate an integer value range, the annotation takes min and max value, so if anyone calls this function using an integer value outside this range, a message error will occur with some hints about what is going wrong.

I'm working in a Java Annotation Process to get the value and compare it with the included max/min ones in @IntRange

This is what I got:

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

You cannot use a Java Annotation Processing because it works only at compile time , so you will be able to get the provided values of @IntRange annotation but not the current one of the method parameter. More information here

What you really need is a custom validator and you can find how to do it here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM