自定义的annotation一般使用反射机制,反射对annotation支持非常好。
看例子:这是一个自定义的annotation
import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; //自定义Annotatiation //设置注解的保存范围,这是个出现在自定义注解里面的一个注解, //它的范围有三种, //RUNTIME:源文件、class文件、JVM。这是比较常用的,也是最重要的。 //CLASS:源文件、class文件 //SOURCE:源文件 @Retention(RetentionPolicy.RUNTIME) //此注释告诉自定义注释只能注释在类上,默认情况下annotation可以放在文件的任何地方 //主要是ElementType所支持的枚举 @Target(ElementType.TYPE) @Documented//当类生成doc文档的时候,可以方便加入方法的注释 @Inherited//此注解是当有子类的时候,还是可以继承此注解的 public @interface MyAnno { public String value();//参数1,字符串 public int value2();//参数2,int类型 public String[] value3();//字符串数组 public String value4() default "默认值";//字符串数组 public MyEnum value5();//规定annotation里面必须是枚举形 }
这是一个测试:
import java.lang.annotation.Annotation; public class TestA{ public static void main(String[] args) { Class<UseMyAnno> class1=UseMyAnno.class; Annotation annos[]=class1.getAnnotations();//取得所有的注解 for (Annotation annotation : annos) { System.out.println(annotation); } //如果改类上的注解是MyAnno则返回true System.out.println(class1.isAnnotationPresent(MyAnno.class)); //取得该类的上的指定注解,例如@MyAnno注解 System.out.println(class1.getAnnotation(MyAnno.class)); //取得指定注解里面的参数值 System.out.println(class1.getAnnotation(MyAnno.class).value2()); } } @MyAnno(value="a",value2=1,value3="{q,p}",value4="b",value5=MyEnum.BLUE) class UseMyAnno{ /** * 通过@Documented来加入注释 * 此方法是显示方法 */ public void show(){ System.out.println("okle"); } } /** * 子类继承,注解因为有@Inherited所以子类也有父类的注解 * @author Administrator * */ class ChildrenAnno extends UseMyAnno{ } //annotation里面的枚举参数 enum MyEnum{ RED,GREEN,BLUE }