注解的神秘之处在于:经过相似注释的方式,能够控制程序的一些行为,运行时的状态,能够为成员赋值,作配置信息等等,与常规编码思惟截然不同。 java
只用别人定义好的注解是搞不懂这些问题的,要想真正知道注解内部的秘密,要本身定义注解,而后在程序中获取注解信息,拿到注解信息后,就能够为我所用了。 框架
下面我简单演示下三类注解的用法:类注解、方法注解、字段(也称之域)注解的定义与适用,并看看如何获取注解的信息。
测试
1、定义注解 编码
package lavasoft.anntest; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 类注解 * * @author leizhimin 2009-12-18 14:15:46 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface MyAnnotation4Class { public String msg(); }
package lavasoft.anntest; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 方法注解 * * @author leizhimin 2009-12-18 14:16:05 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface MyAnnotation4Method { public String msg1(); public String msg2(); }
package lavasoft.anntest; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 字段注解 * * @author leizhimin 2009-12-18 15:23:12 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface MyAnnotation4Field { public String commont(); public boolean request(); }2、写一个类,用上这些注解
package lavasoft.anntest; /** * 一个普通的Java类 */ @MyAnnotation4Class(msg = "测试类注解信息") class TestClass { @MyAnnotation4Field(commont = "成员变量的注解信息", request = true) private String testfield; @MyAnnotation4Method(msg1 = "测试方法注解信息1", msg2 = "测试方法注解信息2") public void testMethod() { System.out.println("Hello World!"); } }3、测试注解
package lavasoft.anntest; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * 测试类 * * @author leizhimin 2009-12-18 14:13:02 */ public class TestOptAnnotation { public static void main(String[] args) throws NoSuchMethodException, NoSuchFieldException { TestClass t = new TestClass(); System.out.println("-----------MyAnnotation4Class注解信息---------"); MyAnnotation4Class an4clazz = t.getClass().getAnnotation(MyAnnotation4Class.class); System.out.println(an4clazz.msg()); System.out.println("-----------MyAnnotation4Method注解信息---------"); Method method = t.getClass().getMethod("testMethod", new Class[0]); MyAnnotation4Method an4method = method.getAnnotation(MyAnnotation4Method.class); System.out.println(an4method.msg1()); System.out.println(an4method.msg2()); System.out.println("-----------MyAnnotation4Field注解信息---------"); Field field = t.getClass().getDeclaredField("testfield"); MyAnnotation4Field an4field = field.getAnnotation(MyAnnotation4Field.class); System.out.println(an4field.commont()); System.out.println(an4field.request()); } }运行结果:
-----------MyAnnotation4Class注解信息---------
测试类注解信息
-----------MyAnnotation4Method注解信息---------
测试方法注解信息1
测试方法注解信息2
-----------MyAnnotation4Field注解信息---------
成员变量的注解信息
true
Process finished with exit code spa