前言
注解也被称为元数据,它在jdk1.5中引入,可以完整的描述无法用Java来表达的程序所需要的信息。
注解在编程中的使用
- 生成文档
按照代码里标识的注解生成代码文档
- 代码分析
按照注解对代码进行分析(反射实现),可以动态的实现业务功能,降低耦合度等用途。
- 编译检查
按照注解让编译器检查代码
Java中的注解主要分两类:
一类是java预定义的注解,它们是@Overrite、@Deprecated和@SupressWarning,共三个;一类是自定义注解。
Jdk预定义注解
Java中用符号@来定义注解,Jdk中内置了三种注解,它们定义在java.lang包中:
- @Overrite:表示当前方法复写了父类方法
- @Deprecated:表示过时
- @SupressWarnings:压制警告。让编译器对一部分警告不要提示。
自定义一个注解
自定义注解使用@interface
关键字进行定义,用@注解名
的组合在要使用该属性的地方打标签即可,比如下面的@ParametersDefault
就表示showStudent
方法上使用这个注解。
//Student.java
public class Student {
@ParametersDefault(name = "zhangsan",age = 19)//打上标签
void showStudent(String name,int age){
System.out.println(name+":"+age+"岁");
}
}
注解@ParametersDefault将为两个属性赋值:name = "zhangsan",age = 19
,这两个值将用做showStudent方法的两个参数。
上面用到的@ParametersDefault的定义如下,
//ParametersDefault.java
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ParametersDefault {
String name();
int age();
}
-
@Target(ElementType.METHOD)
表示注解仅运用于Method上,是元注解 -
@Retention(RetentionPolicy.RUNTIME)
表示这个注解存续的时间一直到运行时,是元注解 -
@interface
是定义注解的关键字 -
ParametersDefault
是注解名 -
name
和age
是注解的属性
注解的本质是一个接口
通过反编译ParametersDefault的字节码文件,可以观察到注解是一个接口。具体操作如下
:
//编译
❯ javac ParametersDefault.java
//反编译
❯ javap ParametersDefault.class
生成一个新的java文件ParametersDefault.java
,
//Compiled from "ParametersDefault.java"
public interface com.teresa.annotationdemo.ParametersDefault extends java.lang.annotation.Annotation {
public abstract java.lang.String name();
public abstract int age();
}
此时可以发现ParametersDefault类
其实继承了java.lang.annotation.Annotation
,
public interface Annotation {
boolean equals(Object obj);
int hashCode();
String toString();
Class<? extends Annotation> annotationType();
}
查看源码,发现Annotation类
是一个接口,也就是说注释的本质就是继承了Annotation
接口的一个接口而已。
注解的属性
上述中ParametersDefault中name方法和age方法,在注解中我们称之为注解的属性或者注解的元素,属性可用的类型有如下几种:
- 所有基本数据类型(byte、char、short、int、float、long、double、boolean)
- String类型
- Class
- enum
- Annnotation
如果使用其他类型,编译器会报错提醒。
注意:编译器要求注解的属性必须有值,也就是说要么在定义属性的时候给它一个默认值,要么在使用注解的时候给属性赋值。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface IAnnotation {
public enum WeekDay{
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY;
}
//String
public String description() default "defaul description";
//Annotation
public ParametersDefault annotion() default @ParametersDefault(name = "teresa",age = 18);
//enum
public WeekDay enums() default WeekDay.MONDAY;
//基础数据类型
public int ints() default 0;
//Class类型
public Class classs() default String.class;
}
元注解–用于注解的注解
普通注解是描述程序信息的注解,元注解则是用来描述注解信息的注解。目前JDK标准中的元注解有四个:@Documented、@Inherited、@Retention、@Target
Target类
指定@Target修饰的注释将运用于什么地方。
Target注释的属性的取值由ElementType枚举类提供,使用格式:@Target(ElementType.TYPE)
ElementType.[
ANNOTATION_TYPE :指定注释用于注释
CONSTRUCTOR:指定注释用于构造方法声明
FIELD:指定注释用于字段声明(包括枚举常量)
LOCAL_VARIABLE:指定注释用于局部变量声明
METHOD:指定注释用于方法声明
PACKAGE:指定注释用于包声明
PARAMETER:指定注释用于参数声明
TYPE:指定注释用于类、接口(包括注释类型)或枚举声明 上
]
Retention类
表示@Retention修饰的注释将会保留到什么时期,取值由RetentionPolicy枚举类提供,使用格式:@Retention(RetentionPolicy.RUNTIME)
RetentionPolicy.[
- SOURCE:表明注释只保留到源码阶段。
- CLASS:表明注释只保留到内存字节码阶段。
- RUNTIME:表明注释保留到代码运行的阶段。
]
Inherited类
指示注释类型被自动继承。如果在注释类型声明中存在 Inherited 元注释,并且用户在某一类声明中查询该注释类型,同时该类声明中没有此类型的注释,则将在该类的超类中自动查询该注释类型。此过程会重复进行,直到找到此类型的注释或到达了该类层次结构的顶层 (Object) 为止。如果没有超类具有该类型的注释,则查询将指示当前类没有这样的注释。
注意,如果使用注释类型注释类以外的任何事物,此元注释类型都是无效的。还要注意,此元注释仅促成从超类继承注释;对已实现接口的注释无效。
Documented类
指示某一类型的注释将通过 javadoc 和类似的默认工具进行文档化。
获取注解对象
只有能保留到运行时阶段的注解可以被反射,并获取到它的动态代理对象。
注释的反射
使用Class.isAnnotation()和Class.isAnnotationPresent(class)方法判断这个class对象上是否有注解。
- class.isAnnotation()
如果此 Class 对象表示一个注释类型则返回 true,接口类型也会返回true。
- class.isAnnotationPresent(Class<? extends Annotation> annotationClass)
如果指定类型的注释存在于此元素上,则返回 true,否则返回 false。
此方法效果等同于:
class.getAnnotion(Class<? extends Annotation> annotationClass) !=null
举个栗子
基于上面的Student上的注解类的使用我将写一个小小范例方便理论+实践并行:
Student:实体类
//Student.java
public class Student {
@ParametersDefault(name = "zhangsan",age = 19)//打上标签
void showStudent(String name,int age){
System.out.println(name+":"+age+"岁");
}
}
ParametersDefault:用于方法的注释类
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ParametersDefault {
String name();
int age();
}
StudentDate:用于类的注释类
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface StudentDate {
String className();
String mathodName();
}
AnnotationDemo:main方法,本例中通过对注解获取Student类的类全限定名和要执行的方法名,然后调用该方法,期间通过方法上的注释获取到运行该方法的参数,并运用。
@StudentDate(className = "com.teresa.annotationdemo.Student",mathodName = "showStudent")
public class AnnotationDemo {
public static void main(String[] args) throws Exception {
System.getProperties().setProperty("jdk.proxy.ProxyGenerator.saveGeneratedFiles", "true");
//debug中查看Annotation的生成过程。AnnotationParser类中生成Annotation的代理类
//获取StudentDate这个注解的类和方法
StudentDate stu = AnnotationDemo.class.getAnnotation(StudentDate.class);
String className = stu.className();
String methodName = stu.mathodName();
Class studentClazz = Class.forName(className);
Method method = studentClazz.getDeclaredMethod(methodName,new Class[]{String.class,int.class});
ParametersDefault def = method.getAnnotation(ParametersDefault.class);
String name = def.name();
int age = def.age();
method.invoke(new Student(),name,age);
}
}
//运行结果:
zhangsan:19岁
后续:
到现在为止,我们还只学会注解的定义和使用,还有很多问题未解决,比如:
1、为什么注解是接口,但是使用的时候它的方法却称作注解的属性或者元素?
2、使用的方式也很特别,为什么是方法名对应赋值而不是像普通类一样使用属性赋值
3、基于问题2,为什么注解是个接口却能当做对象使用呢?
我将会在下一篇java注解的文中进入字节码中深入探究,看看究竟是什么魔法让注释能如此神奇!