注解
1.元注解
元注解有:@Target,@Retention,@Documented,@Inherited
@Target 表示该注解用于什么地方,以jdk 1.8为例子 ElemenetType 参数包括:
@Target(ElementType.TYPE)——接口、类、枚举、注解
@MyAnnotation
public interface/class/enum/@interface test {
}
@Target(ElementType.FIELD)——字段、枚举的常量
public class test {
@MyAnnotation
private String userName;
}
public enum AppResponseStatus {
@MyAnnotation
SUCCESS(0)
}
@Target(ElementType.METHOD)——方法
@MyAnnotation
public void test(String name) {
}
@Target(ElementType.PARAMETER)——方法参数
public void test(@MyAnnotation String name) {
}
@Target(ElementType.CONSTRUCTOR) ——构造函数
public void test(String name) {
@MyAnnotation
public test(){
}
}
@Target(ElementType.LOCAL_VARIABLE)——局部变量
public void test(String name) {
@MyAnnotation
int a = 0;
}
@Target(ElementType.ANNOTATION_TYPE)——注解
@MyAnnotation
public @interface DataSource {
}
@Target(ElementType.PACKAGE)——包
@MyAnnotation
package com.basicclass.multithreading.singletonpattern;
@Target(ElementType.TYPE_PARAMETER)——泛型
public class Generic<@MyAnnotation T> {
}
@Target(ElementType.TYPE_USE)——表示该注解能使用在使用类型的任意语句中
例如:
ArrayList<@MyAnnotation String> list = new ArrayList<>();
@Retention 表示在什么级别保存该注解信息。可选的 RetentionPolicy 参数包括:
RetentionPolicy.SOURCE 注解将被编译器丢弃
RetentionPolicy.CLASS 注解在class文件中可用,但会被VM丢弃
RetentionPolicy.RUNTIME VM将在运行期也保留注释,因此可以通过反射机制读取注解的信息。
@Documented 将此注解包含在 javadoc 中
生成的javaDoc 对应的index.html 会展示对应的注解
@Inherited 允许子类继承父类中的注解
CSDN-TheMain183-@Inherited详解
反射
反射常用注解
1.isAnnotationPresent A.isAnnotationPresent(B.class);意思就是:注释B是否在此A上。如果在则返回true;不在则返回false。
2.getAnnotations 只有当父类的注解中用@Inherited修饰,子类的getAnnotations()才能获取得到父亲的注解以及自身的注解
3.getDeclaredAnnotations() 只会获取自身的注解,无论如何都不会获取父亲的注解