注解处理器,获取方法参数的修饰符

Annotation Processor, Getting Modifiers of Method Parameters

我目前在一个项目中使用 Java 的自定义注释。我想强制我的注释的用户,如果他用@Foo 注释了方法,他必须在方法参数列表中至少声明一个 final boolean b 。所以它应该看起来像这样:

@Foo
public void foo(final boolean b) { }

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

使用注释处理器,我可以检索变量的类型,但不能检索最终修饰符。如果我想检索如下代码所示的修饰符集,尽管参数中存在最终修饰符,但该集合将始终为空。

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

有什么想法,为什么会这样?

不幸的是,final 参数的修饰符似乎没有被 javax.lang.model 类 忠实地表示(即,根据源文件)。 documentation of the javax.lang.model.element package 说(加粗我的):

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