1

I have a class that is annotated with my annotation and then I want to get all the class fields and then check if their methods contain a call to a specific service.

The issue is that the method body is always null in this case.

Just a small note the classes of the fields live in another module.

public boolean process( Set<? extends TypeElement> annotations, RoundEnvironment roundEnv )
{
    Set<? extends Element> annotatedClasses = getAnnotatedClasses( annotations, roundEnv );
    
    annotatedClasses.forEach(annotatedClass -> {
        List<? extends Element> fields = getFields( annotatedClass );

        fields.forEach( field -> {
            List<ExecutableElement> methods = getMethods( field );

            methods.forEach( method -> {
                MethodScanner methodScanner = new MethodScanner();
                MethodTree methodTree = methodScanner.scan( method, this.trees );
                BlockTree body = methodTree.getBody();
            }
        }
    }
}

The MethodScanner class comes from here: Accessing source code from Java Annotation Processor

Any way of getting the method source code?

Thanks

2
  • 1
    The compiler tree api, in the answers you are linking to, requires that the source for the methods in question are presently being compiled, otherwise the AST will not be available. This is probably what you are encountering. Commented Dec 4, 2022 at 0:21
  • It might be possible to open the class files of classes which are not currently compiled. You could analyze these class files with ASM instead of using the Compiler Tree API. However, ASM would not work on classes to be compiled, so you would have to maintain two separate branches, one for classes currently compiled, one for classes in other modules. Commented Dec 26, 2022 at 1:07

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.