Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Annotation Processor, Getting Modifiers of Method Parameters

I'm currently at a project where I work with Java's custom annotations. I want to force the user of my annotation that he has to declare at least a final boolean b inside the method parameters list if he has annotated the method with @Foo. So 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 retrieve the type of the variable but not the final modifier. If i want to retrieve the set of modifiers as shown in the below code, the set will always be empty although the final modifier is present on the parameter.

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

Any ideas, why this is the case?

like image 548
michael Avatar asked Jun 21 '17 09:06

michael


Video Answer


1 Answers

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

When used in the context of annotation processing, an accurate model of the element being represented must be returned. As this is a language model, the source code provides the fiducial (reference) representation of the construct in question rather than a representation in an executable output like a class file. Executable output may serve as the basis for creating a modeling element. However, the process of translating source code to executable output may not permit recovering some aspects of the source code representation. For example, annotations with source retention cannot be recovered from class files and class files might not be able to provide source position information. Names of parameters may not be recoverable from class files. The modifiers on an element may differ in some cases including:

  • strictfp on a class or interface
  • final on a parameter
  • protected, private, and static on classes and interfaces
like image 54
rolve Avatar answered Oct 17 '22 04:10

rolve