1、自定义注解Car_color
package com.dist.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//@Target(ElementType.PARAMETER) //表示这个注解的只适用于属性,也可以写多个({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.RUNTIME) //表示注解只在执行期起作用
public @interface Car_color {
//返回值String就是参数的类型,只能是基本类型
//这里用default默认参数是“白色”
String color() default "白色"; //color方法其实是声明了一个配置参数
}
2、将注解带到类或接口或字段或方法上
//@Car_color(color="黑色")
public class Car {
@Car_color(color="黑色")
private String color;
}
3、获取方法
1)类上注解获取值
public class Test {
public static void main(String[] args) throws ClassNotFoundException {
Class cls=Class.forName("com.dist.annotation.Car"); //获取类对象
Car_color annotation = (Car_color) cls.getAnnotation(Car_color.class);
System.out.println(annotation.color());
}
}
2)获取字段上的
public class Test {
public static void main(String[] args) throws ClassNotFoundException {
Class cls=Class.forName("com.dist.annotation.Car"); //获取类对象
Field[] field=cls.getDeclaredFields(); //获取类的属性数组
for(Field f:field){ //循环属性
if(f.isAnnotationPresent(Car_color.class)){ //获取属性的注解,并判断是否是Car_color.class注解
Car_color car=f.getAnnotation(Car_color.class); //获取Car_color注解对象
System.out.println("汽车颜色:"+car.color()); //输出注解的color配置参数
}
}
}
}