本示例演示如何获取类和方法的注解。我们使用反射API来获取类和方法信息,从中我们可以读取有关附加到该类或方法的注解的信息。
package org.nhooo.example.lang.annotation; import java.lang.annotation.Annotation; import java.lang.reflect.Method; @HelloAnnotation(value = "Hello", greetTo = "Universe") public class GettingAnnotation { public static void main(String[] args) { GettingAnnotation demo = new GettingAnnotation(); Class clazz = demo.getClass(); Annotation[] annotations = clazz.getAnnotations(); for (Annotation anno : annotations) { System.out.println("Annotation Type: " + anno.annotationType()); } HelloAnnotation anno = (HelloAnnotation) clazz.getAnnotation(HelloAnnotation.class); System.out.println("Anno Value : " + anno.value()); System.out.println("Anno GreetTo: " + anno.greetTo()); try { Method m = clazz.getMethod("sayHi"); anno = m.getAnnotation(HelloAnnotation.class); System.out.println("Anno Value : " + anno.value()); System.out.println("Anno GreetTo: " + anno.greetTo()); } catch (NoSuchMethodException e) { e.printStackTrace(); } demo.sayHello(); } @HelloAnnotation(value = "Hi", greetTo = "Alice") public void sayHi() { } @HelloAnnotation(value = "Hello", greetTo = "Bob") public void sayHello() { try { Method m = getClass().getMethod("sayHello"); HelloAnnotation anno = m.getAnnotation(HelloAnnotation.class); System.out.println(anno.value() + " " + anno.greetTo()); } catch (NoSuchMethodException e) { e.printStackTrace(); } } }
您可以HelloAnnotation在下面的示例中找到上面使用的注解:如何创建简单的注解?
我们程序的结果是:
Annotation Type: interface org.nhooo.example.lang.annotation.HelloAnnotation Anno Value : Hello Anno GreetTo: Universe Anno Value : Hi Anno GreetTo: Alice Hello Bob