Annotation Processor, Getting Modifiers of Method Parameters

北慕城南 提交于 2019-12-21 12:39:30

问题


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? Am I missing something?


回答1:


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


来源:https://stackoverflow.com/questions/44672092/annotation-processor-getting-modifiers-of-method-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!