1概念:Java提供了一种原程序中的元素关联任何信息和任何元数据的途径和方法。
2常用分类:
源码注解:只有在源码中存在的注解
编译时注解:在源码和编译生成的.class文件中存在
运行时注解:在运行阶段起作用,甚至可以影响到程序运行的逻辑。
元注解:注解的注解
@Target:
@Target说明了Annotation所修饰的对象范围:Annotation可被用于 packages、types(类、接口、枚举、Annotation类型)、类型成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch参数)。在Annotation类型的声明中使用了target可更加明晰其修饰的目标。
@Retention:
@Retention定义了该Annotation被保留的时间长短:决定注解是源码注解、编译时注解还是运行时注解
@Documented:
@Documented用于描述其它类型的annotation应该被作为被标注的程序成员的公共API,因此可以被例如javadoc此类的工具文档化。Documented是一个标记注解,没有成员。
@Inherited:
@Inherited 元注解是一个标记注解,@Inherited阐述了某个被标注的类型是被继承的。如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类。
3自定义注解:
语法:public @interface 注解名 {定义体} 成员变量以无参无异常的方式声明 用default给成员变量一个默认值 合法变量类型有8大原始类型(比如int、float等)、string、Class、Annotation、Enumeration和以上这些类型的数据 如果只有一个成员变量,必须value(),也可以没有成员。
自定义注解如下:
@Retention(value = RetentionPolicy.RUNTIME)//运行时注解 public @interface Description { String hh(); String desc(); int age() default 22; }4注解的使用:
运行时注解,通过java反射机制获取注解中变量值。 a 给类添加注解
@Description(desc = "this a boy lei", hh = "boy lei is hhing") public class Boy implements Person{ @Override @Description(desc = "this a boy", hh = "boy is hhing") public String sya(String s) { return s; } @Override public String getAge() { return "99"; } }b反射获取注解
public static void main(String[] args) { // TODO Auto-generated method stub Boy b=new Boy(); System.out.print(b.sya("hello_world")); Class<? extends Boy> c=b.getClass();//获取类对象 if(c.isAnnotationPresent(Description.class)){ Description d=(Description) c.getAnnotation(Description.class); System.out.println(d.age()+""); System.out.println(d.desc()); System.out.println(d.hh()); } Method[] methods=c.getDeclaredMethods();//获取类对象中所有申明方法 for(Method m:methods){ if(m.isAnnotationPresent(Description.class)){ Description dd=m.getAnnotation(Description.class); System.out.println(dd.age()+""); System.out.println(dd.desc()); System.out.println(dd.hh()); } } } c运行效果