Java Runtime注释如何在内部工作?

我知道编译时注释function,运行注释处理器和使用reflectionAPI。 但我不确定JVM如何获得有关运行时注释的通知。 注释处理器也可以在这里工作吗?

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

一个示例声明是:

 package annotations; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface Developer { String value(); } 

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

怎么用?

 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"); } } 

我们可以使用reflection包来读取注释。 当我们开发基于注释自动化某个过程的工具时,它非常有用。

 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(); } } } } } 

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

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