注解
注释:给代码添加说明和解释,注释帮助开发人员理解程序。(Comment)【给程序员看的】
注解:给代码添加说明,这个说明给程序使用。(Annotation)【给虚拟机看的】
从 JDK 5.0 开始,Java 增加了对元数据(MetaData) 的支持, 也就是Annotation(注解)。
三个基本的 Annotation:
@Override:限定重写父类方法, 该注解只能用于方法
@Deprecated:用于表示某个程序元素(类, 方法等)已过时
@SuppressWarnings: 抑制编译器警告.
什么是注解
Annotation其实就是代码里的特殊标记, 它用于替代配置文件,也就是说,传统方式通过配置文件告诉类如何运行,有了注解技术后,开发人员可以通过注解告诉类如何运行。在Java技术里注解的典型应用是:可以通过反射技术去得到类里面的注解,以决定怎么去运行类
注解技术的要点
如何定义注解
如何反射注解,并根据反射的注解消息,决定如何去运行类
自定义注解
定义新的 Annotation 类型使用@interface关键字
声明注解的属性
注解属性的作用:原来写在配置文件中的信息,可以通过注解的属性进行描述。
Annotation的属性声明方式:String name();
属性默认值声明方式:String name() default “xxx”;
特殊属性value:如果注解中有一个名称value的属性,那么使用注解时可以省略value=部分,如@MyAnnotation(“xxx")
特殊属性value[];
定义的注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
//属性
String name() ;
int age() ;
}
Student类
public class Student {
@MyAnnotation(name = "zhangsan", age = 25)
public void show() {
System.out.println("学生信息:");
}
}
根据注解获取属性值
public class Demo {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException {
//获取字节码文件的类对象
Class<?> aClass = Class.forName("am.annotation.Student");
//找到注解所在的方法
Method show = aClass.getMethod("show");
//通过方法的getAnnotation(注解名称.class) 获取注解
MyAnnotation annotation = show.getAnnotation(MyAnnotation.class);
//通过注解拿到注解中的属性
//NullPointerException 运行的时候就没有了,需要给注解加上元注解
String name = annotation.name();
int age = annotation.age();
System.out.println("age = " + age + "name = " + name);
}
}
jdk中的元Annotation(注解)
元 Annotation指修饰Annotation的Annotation
@Retention: 只能用于修饰一个 Annotation 定义, 用于指定该 Annotation 可以保留的域, @Rentention 包含一个 RetentionPolicy 类型的成员变量, 通过这个变量指定域
RetentionPolicy.CLASS: 编译器将把注解记录在 class文件中. 当运行 Java 程序时, JVM 不会保留注解. 这是默认值
RetentionPolicy.RUNTIME:编译器将把注解记录在 class文件中. 当运行 Java 程序时, JVM 会保留注解. 程序可以通过反射获取该注释
RetentionPolicy.SOURCE: 编译器直接丢弃这种策略的注释
@Target:指定注解用于修饰类的哪个成员.@Target 包含了一个名为value,类型为ElementType的成员变量。
@Documented:用于指定被该元 Annotation 修饰的Annotation类将被 javadoc 工具提取成文档
@Inherited:被它修饰的 Annotation 将具有继承性.如果某个类使用了被 @Inherited 修饰的Annotation,则其子类将自动具有该注解
使用反射获取注解信息:
@Retention(RetentionPolicy.RUNTIME)
public @interface PersonInfo {
String name();
int age() default 20;
String gender();
}
public class PersonOpe {
@PersonInfo(name="李四",age=20,gender="男")
public void show(String name,int age,String gen) {
System.out.println(name);
System.out.println(age);
System.out.println(gen);
}
}
public class Demo2 {
public static void main(String[] args) throws Exception{
PersonOpe ope=new PersonOpe();
//获取.class对象
Class<?> class1=PersonOpe.class;
//找到带有注解的方法
Method method = class1.getMethod("show", String.class,int.class,String.class);
//方法.getAnnotation(注解名称.class)
PersonInfo annotation = method.getAnnotation(PersonInfo.class);
String name=annotation.name();
int age=annotation.age();
String gender=annotation.gender();
method.invoke(ope, name,age,gender);
}
}