-
注解(标注): jdk1.5新增 1.注释说明的作用 2.标志检查的作用 3.注解可以保留在class文件中,注释不能保存在class文件中 4.配置主键的时候可以通过传递实参,程序中可以通过反射获取到传递的数据进行使用 5.大量的代替了配置文件的存在
-
使用: @注解名(数据)
-
位置: 任意位置都能使用(根据需求指定使用位置)
-
分类: 参数个数分类: 标志注解|标识注解 : 没有参数 单值注解 : 一个参数 完整注解 : 多个参数
-
jdk内置注解 普通注解 : @Override 强制检测被注解的方法是否为重写方法 @Deprecated 标志已过时 @SuppressWarnings("all") 抑制所有警告 @FunctionalInterface 强制检测一个接口是否为函数式接口
-
元注解 : 注解注解的注解 @Target 用于描述注解的使用范围(即:被描述的注解可以用在什么地方) @Retention 用于描述注解的生命周期 一个注解类型的声明周期必须为运行期,才能运行期间通过反射操作 @Documented 表示使用该注解的元素应被javadoc或类似工具文档化 @Inherited 表示一个注解类型会被自动继承 自定义注解
public class Class001_Anno {
public static void main(String[] args) {
test();
List list = new ArrayList();
}
@Deprecated
static void test(){
List list = new ArrayList();
List list2 = new ArrayList();
}
}
8.2自定义注解
-
1.使用@interface定义注解类型
-
2.定义的注解类型默认隐式的实现了java.lang.annotation.Annotation
-
3.自定义的注解类型不能显示的继承其他父类以及实现其他接口
-
4.可以在注解类型的内部提供属性或者字段
-
5.注解类型中属性的定义 : 数据类型 属性名();
-
6.注解类型中的属性的数据类型 : 基本数据类型 , String , 枚举类型 , 注解类型 ,或者以上类型的数组
-
7.如果只有一个属性,建议属性名定义为value,赋值的时候就可以省略属性名=,直接赋值
-
8.通过default关键字为属性添加一个默认值
@MyAnnotation
public class Class002_DefinedAnnotation {
@MyAnnotation(12)
void test(){
}
public static void main(String[] args) {
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD})
@interface MyAnnotation{
int value() default 1;
}
@interface haha{}
8.2.1注解解析器
-
注解解析器: 了解 水果清单: 每天上货的水果,以及数量
注意: 注解需要设置声明周期为运行期才能通过反射操作 @Retention(RetentionPolicy.RUNTIME)
public class Class01_FruitList {
public static void main(String[] args) throws IllegalAccessException {
//水果清单
FruitList f = new FruitList();
f.apple = 0;
System.out.println(f);
f = test(f,FruitList.class);
System.out.println(f);
}
//通过反射操作注解
public static FruitList test(FruitList list,Class<FruitList> cls) throws IllegalAccessException {
//获取FruitList类中所有的属性
Field[] fields = cls.getDeclaredFields();
//遍历获取list对象的所有属性值
for(Field field:fields){
Object value = field.get(list);
//遍历判断当前属性值是否为null
if(value==null){
//判断是否存在Num类型的注解修饰
if(field.isAnnotationPresent(Num.class)){
//获取属性上面的Num注解
Num n = field.getAnnotation(Num.class);
//为list对象的当前属性赋值
field.set(list,n.value());
}
}
}
return list;
}
}
//水果清单
class FruitList{
@Num(3)
Integer apple;
Integer pair;
@Num
Integer banana;
public FruitList() {
}
public FruitList(int apple, int pair, int banana) {
this.apple = apple;
this.pair = pair;
this.banana = banana;
}
@Override
public String toString() {
return "FruitList{" +
"apple=" + apple +
", pair=" + pair +
", banana=" + banana +
'}';
}
}
//注解 : 标识水果默认的上货数量
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Num{
int value() default 2;
}
