简体   繁体   中英

Java Annotation Element Method return

I have a custom annotation like below.

@customelement(folder = "/path/")
public testMethod() {

}

How I can extract folder value ie"/path/", using AbstractProcessor, below?

public class CompileTimeAnnotationProcessor extends AbstractProcessor {

    @Override
    public boolean process(Set<? extends TypeElement> annotations, 
                           RoundEnvironment roundEnv) {
        Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(CustomAnnotation.class);
        for(Element te : elements){
          for (Element e : te.getEnclosedElements()) {
                     if (e.getSimpleName().toString().equals("folder")) {
                       //Here fetch method return value
                  }
           }
        }
        return true;
    }

}

I guess that you want to do sth like:

    @Override
    public boolean process(Set<? extends TypeElement> annotations, 
                           RoundEnvironment roundEnv) {
        Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(CustomAnnotation.class);
        for(Element te : elements){
          CustomAnnotation annotation = te.getAnnotation(CustomAnnotation.class);
          String folder = annotation.folder();
          //... do sth with folder in context of te. 
          //te represent annotated method, e.g. testMethod from your example
        }
        return true;
    }

Also remember to annotate your CompileTimeAnnotationProcessor with @SupportedAnnotationTypes("package.CustomAnnotation") and @SupportedSourceVersion(SourceVersion.RELEASE_7) (or whatever version of Java syntax are you going to support).

In case of further problems, I recommend to read this great tutorial blog post .

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