Annotation handler, retrieving method parameter modifiers

I am currently in a project where I work with custom Java annotations. I want to force the user of my annotation that he should declare at least final boolean b in the method parameter list if he annotated the method with @Foo. Therefore, it should look something like this:

 @Foo public void foo(final boolean b) { } @Foo public void bar() { } // This should result in an error 

With my annotation processor, I can get the type of a variable , but not the last modifier . If I want to get a set of modifiers, as shown in the code below, the set will always be empty, although the last parameter is present in the parameter.

 for (VariableElement parameter : method.getParameters()) { Set<Modifier> modifiers = parameter.getModifiers(); // This set is always empty } 

Any ideas why this is so? Did I miss something?

+5
source share
1 answer

Unfortunately, it seems that the final parameter modifiers are not reliably represented (i.e. according to the source file) by the javax.lang.model classes. The javax.lang.model.element package javax.lang.model.element says (bolding mine):

When used in the context of annotation processing, the exact model of the represented element should be returned. Since this is a model language, the source code provides a FIDUCIAL (link) representation of the construct in question, and not an executable output representation, like a class file. Executable output can serve as the basis for creating a modeling element. However, the process of translating source code to executable output may not allow you to restore some aspects of the presentation of the source code. For example, source-preserving annotations cannot be retrieved from class files, and class files may not be able to provide source location information. Parameter names cannot be recovered from class files. Modifiers in an element may differ in some cases, including:

  • strictfp for class or interface
  • final by parameter
  • protected , private and static for classes and interfaces
+4
source

Source: https://habr.com/ru/post/1269058/


All Articles