9

I am processing java annotations using the Pluggable Annotation Processing API. Is it somehow possible to also process annotations used inside a method body?

thanks for help. Peter

wrm
  • 1,898
  • 13
  • 24

2 Answers2

4

I think, i found the solution. As i thought, it is not possible with the current javac. local annotations are just simple comments and wont be processed by the pluggable annotation processing api. BUT there are interesting efforts in JSR308, handling type annotations that support marvelous things as parameters on type-variables, local variables, annotated-type-checking and casting... and as it looks, it will be incorporated into openJDK 8. nice

mernst
  • 7,437
  • 30
  • 45
wrm
  • 1,898
  • 13
  • 24
  • JSR 308 does not directly support annotation processing (though it does correct a long-standing bug in which local variable annotations were not stored in the classfile). It does have the other features you mention, and it is part of Java 8. The [Checker Framework](http://checkerframework.org) is built on JSR 308 and does provide convenient visitors that process annotations within method bodies. – mernst Sep 30 '14 at 07:26
1

In JSR269, the relevant interface would be javax.lang.model.element.VariableElement, which inherits getAnnotation(Class<A> annotationType) for accessing such annotations:

for (VariableElement variable : ElementFilter.fieldsIn(methods)) {
    final AnnotationType annotation = variable.getAnnotation(AnnotationType.class);
    if (annotation != null) {
        // ...
    }
}
eggyal
  • 122,705
  • 18
  • 212
  • 237
  • 3
    thanks for that answer. But `methods` is a set of elements meaning, it should already contain the annotated fields (which makes method a bad name for that set). so `fieldsIn` does not return "fields (= local variables) in a method" but just filter a set of given elements. And the problem with that is, that the API wont give me annotated local variables (as parameter of the `process`-method). For now, it looks like i have to process ALL (not just annotated) classes and search for local-variable-annotations manually (though i dont know how exactly). or is there a way to use your example? – wrm Oct 19 '11 at 07:38