Java 9+ 无法获取方法局部变量的注解

标签 java reflection annotations

自 Java 9 以来,以 LOCAL_VARIABLE 作为目标的注解的保留方式发生了变化。 Now the bytecode representation will hold information about annotated local variables in each method.此外,规范声明 如果 m 有一个值为 java.lang.annotation.RetentionPolicy.RUNTIME 的元素,则 Java SE 平台的反射库必须在运行时提供一个。,其中,如果我理解正确,确认至少该方法的局部变量上的注释应该可以通过反射获得。

但是,我一直在尝试使用反射来查找注释(或注释的局部变量,或它们的值),但没有成功。

因此,是否有人知道如何执行此操作或是否可能?我正在使用 Java 11。

例如,这是我的主类,我在其中尝试从测试方法中获取 @Parallel 注释。

public class Main {

public static void main(String[] args) {

    try {
        System.out.println("Main.class.getDeclaredMethod(\"test\").getAnnotations().length = " +
                Main.class.getDeclaredMethod("test").getAnnotations().length);

        System.out.println("Main.class.getDeclaredMethod(\"test\").getDeclaredAnnotations().length = " +
                Main.class.getDeclaredMethod("test").getDeclaredAnnotations().length);

        Annotation annotation = Main.class.getDeclaredMethod("test").getAnnotation(Parallel.class);
        System.out.println("annotation = " + annotation);

    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }
}

void test() {
    @Parallel int a = 2;

    @Parallel int b = 4;
}
}

这是我的注释实现。我刚刚将所有内容添加为目标,因为我只是在测试它:

@Target({ ElementType.LOCAL_VARIABLE, ElementType.TYPE, ElementType.TYPE_USE, ElementType.TYPE_PARAMETER,
    ElementType.FIELD, ElementType.PARAMETER, ElementType.PACKAGE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface Parallel {
}

运行 javap -l -v -c -s Main.class 将显示:

void test();
descriptor: ()V
flags: (0x0000)
Code:
  stack=1, locals=3, args_size=1
     0: iconst_2
     1: istore_1
     2: iconst_4
     3: istore_2
     4: return
  LineNumberTable:
    line 22: 0
    line 24: 2
    line 25: 4
  RuntimeVisibleTypeAnnotations:
    0: #27(): LOCAL_VARIABLE, {start_pc=2, length=3, index=1}
      Parallel
    1: #27(): LOCAL_VARIABLE, {start_pc=4, length=1, index=2}
      Parallel

很明显局部变量的注解信息是有的,只是不知道反射能不能取回(或者有没有其他方法在运行时获取)

最佳答案

.class 文件包含的信息比通过反射公开的信息多,但反射不会公开有关方法内局部变量的信息。

我没有找到正式说明的地方,但可以指向 java.lang.reflect.Method 的 Javadoc它没有公开任何关于局部变量的方法。查看其余的 the reflection package ,没有什么比 Method 更合适了。

关于Java 9+ 无法获取方法局部变量的注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58274902/

相关文章:

java - 使用构造函数参数模拟嵌套类并测试方法

java - Eclipse 上禁止和不鼓励引用的访问规则

java - javax.persistence @Column 上的长度字段是否定义了最大值?

Android:如何摆脱@Generated ("org.jsonschema2pojo")?

java - 不需要 Autowiring ServletRequest 但抛出 BeanCreationException

java - 代码意外停止而不是无限运行

java - 使用 Java 反射找到最匹配的 writeMethod

c# - ASP.Net 和 GetType()

java - Java中如何通过内部类实例获取外部类实例

Java POJO 属性的 xml 注释