JAVA注解(二)-----自定义注解
1、定义注解
public @interface MyTag{ //成员变量在注解定义中以无形参的方法形式来声明 String name() default "yeeku"; int age() default 32; }
根据注解是否包含成员变量可分为标记注解(无成员变量)、元数据注解(有成员变量)
2、提取注解信息
//获取Test类的info方法的所有注解 Annotation[] aArray = Class.forNmae("Test").getMethod("info").getAnnotations(); //遍历所有的注解 for(Annotation an : aArray){ System.out.println(an); }
如果需要获取某个注解里的元数据,可以将注解强制类型转换为所需的注解类型,然后通过注解对象的抽象方法来访问这些元数据
//获取tt对象的info方法的所有注解 Annotation[] annotation = tt.getClass().getMethod("info").getAnnotations(); //遍历所有的注解 for(Annotation tag : annotation){ //如果tag注解是MyTag1类型 if(tag instanceof MyTag1){ //输出tag对象的method1和method2两个成员变量的值 System.out.println(((MyTag1)tag).method1()); System.out.println(((MyTag1)tag).method1()); } }
3、使用注解的示例
浙公网安备 33010602011771号