注释处理器,获取方法参数的修饰符 [英] Annotation Processor, Getting Modifiers of Method Parameters

查看:29
本文介绍了注释处理器,获取方法参数的修饰符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

不幸的是,final 参数修饰符似乎没有如实表示(即根据源文件)<代码>javax.lang.model 类.文档javax.lang.model.element 说(我的粗体):

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 在类或接口上
  • final 在参数上
  • protectedprivatestatic 在类和接口上
  • strictfp on a class or interface
  • final on a parameter
  • protected, private, and static on classes and interfaces

这篇关于注释处理器,获取方法参数的修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆