注解
一、四种元注解
1.@Target,定义所修饰的对象范围
(1)ElementType.TYPE —— 修饰类、接口(包括注解)、枚举
(2)ElementType.CONSTRUCTOR —— 修饰构造函数
(3)ElementType.FIELD —— 修饰成员变量
(4)ElementType.METHOD —— 修饰方法
(5)ElementType.LOCAL_VARIABLE —— 修饰成员变量
(6)ElementType.PACKAGE —— 修饰包
(7)ElementType.PARAMETER —— 修饰参数
2.@Retention,定义该注解的保留时间
(1)RetentionPolicy.SOURCE —— 注解在源文件中有效,保留在源文件中
(2)RetentionPolicy.CLASS —— 注解在class中有效,保留在class文件中
(3)RetentionPolicy.RUNTIME —— 注解在运行时有效
3.@Documented,用于定义该注解可以被文档话(例如可以被javadoc等工具文档化,是一个标记注解,没有成员)
4.@Inherited,@Inherited 元注解是一个标记注解,@Inherited阐述了某个被标注的类型是被继承的。如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类。
二、注解的使用
1、注解类
/**
* 注解类
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface AnnotationClass {
String className() default "MainClass";
int classMethodNum() default 0;
}
/**
* 获取注解类信息
*
* @param cls
*/
public static void getAnnotationClassData(Class cls) {
boolean hasAnnotation = cls.isAnnotationPresent(AnnotationClass.class);
if (hasAnnotation) {
AnnotationClass annotationClass = (AnnotationClass) cls
.getAnnotation(AnnotationClass.class);
if (annotationClass != null) {
String className = annotationClass.className();
int classMethodNum = annotationClass.classMethodNum();
System.out.println("注解Class---className:" + className
+ ",classMethodNum:" + classMethodNum);
}
}
}
2、注解成员变量
/**
* 注解成员变量
*
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AnnotationFiled {
String defaultValue() default "";
}
/**
* 获取成员变量数据
*
* @param cls
*/
public static void getAnnotationFiledData(Class cls) {
Field[] fields = cls.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);// 如果成员变量为私有,必须进行此操作
AnnotationFiled annotationFiled = field
.getAnnotation(AnnotationFiled.class);
if (annotationFiled != null) {
String value = annotationFiled.defaultValue();
System.out.println(field.getName() + ":" + value);
}
}
}
3、注解方法
/**
* 注解方法
*/
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AnnotationMethod {
String name() default "";
int id() default 0;
}
/**
* 获取方法注解数据
* @param cls
*/
public static void getAnnotationMethodData(Class cls) {
Method[] methods = cls.getDeclaredMethods();
for (Method method : methods) {
method.setAccessible(true);
AnnotationMethod annotationMethod = method
.getAnnotation(AnnotationMethod.class);
if (annotationMethod != null) {
String name = annotationMethod.name();
int id = annotationMethod.id();
System.out.println("方法名:" + method.getName() + ",name:" + name
+ ",id:" + id);
}
}
}