Java 运行时注释在内部如何工作?

use*_*988 4 java jvm annotations

我知道编译时注释功能,运行注释处理器并使用反射 API。但我不确定 JVM 如何获得关于运行时注释的通知。注释处理器也在这里工作吗?

The*_*Roy 7

使用元注释@RetentionRetentionPolicy.RUNTIME,标记的注释由 JVM 保留,因此它可以被运行时环境使用。这将允许在运行时检查注释信息(元数据)。

一个示例声明是:

package annotations;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface Developer {
    String value();
}
Run Code Online (Sandbox Code Playgroud)

运行时 值名称本身表明,当保留值为“运行时”时,此注释将在运行时在 JVM 中可用。我们可以使用反射包编写自定义代码并解析注解。

它是如何使用的?

package annotations;
import java.net.Socket;

public class MyClassImpl {

    @Developer("droy")
    public static void connect2Exchange(Socket sock) {
        // do something here
        System.out.println("Demonstration example for Runtime annotations");
    }
}
Run Code Online (Sandbox Code Playgroud)

我们可以使用反射包来读取注解。当我们开发工具以基于注释自动化某个过程时,它很有用。

package annotations;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class TestRuntimeAnnotation {
    public static void main(String args[]) throws SecurityException,
    ClassNotFoundException {
        for (Method method : Class.forName("annotations.MyClassImpl").getMethods()) {
            if(method.isAnnotationPresent(annotations.Developer.class)){
                try {
                    for (Annotation anno : method.getDeclaredAnnotations())  {
                        System.out.println("Annotation in Method '" + method + "' : " + anno);

                        Developer a = method.getAnnotation(Developer.class);
                        System.out.println("Developer Name:" + a.value());
                    }
                } catch (Throwable ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


方法'public static void annotations.MyClassImpl.connect2Exchange(java.net.Socket)'中的输出注释:@annotations.Developer(value=droy)
开发者名称:droy

  • 使用 Java 反射,您可以在运行时访问附加到 Java 类的注释。 (3认同)

Gri*_*ief 2

它们作为元数据存储在.class文件中。您可以阅读官方文档了解详细信息:https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-3.html#jvms-3.15