Access interface of return value of enclosedElement in java annotationprocessor using TypeVisitor?

57 Views Asked by At

I'm currently building an annotation processor, and I want to filter all methods that return a record that implement a certain interface.

In the IntelliJ Debug window I can see that the restype variable has an interfaces_field where I can get the classtype of the return value.

IntelliJ Debug Window

I would like to to access this value at build time, but I run into this error when accessing the restype directly like I do in the expression window:

e: file:///home/thomas/IdeaProjects/spring-view-component/core/src/main/kotlin/de/tschuehly/spring/viewcomponent/core/processor/ViewComponentProcessor.kt:3:33 
Symbol is declared in module 'jdk.compiler' which does not export package 'com.sun.tools.javac.code'

The next issue is that I don't know how to access the interfaces_field attribute in the restype value.

I think the solution would be a TypeVisitor, but I didn't find any examples with my Google fu.

Someone knows how to this?

1

There are 1 best solutions below

1
Colin Alworth On

It isn't quite clear to me what you're asking - your groovy(?) code in the expression window appears to filter methods and return their method typemirrors (i.e. a list of javax.lang.model.type.ExecutableType).

If so, you can call ExecutableType.getReturnType() on each instance, then verify that the returned type is a DeclaredType (and not a primitive, or array, typevariable, etc). DeclaredType doesn't give access directly to its implemented interfaces either, but that probably only matters if you need the generic args passed to the interface. If not, you can just call DeclaredType.asElement() to get the TypeElement (now an element instead of a mirror), and then call TypeElement.getInterfaces() on that to get the directly implemented interfaces - note that you'll need to visit the superclass and any other interfaces recursively to pick up transitively implemented interfaces.