注解

1.元注解

  • @Target 说明修饰对象范围
  • @Retention : 定义该注解被保留的时间长短,SOURCE 源文件保留,CLASS class文件保留,RUNTIME 运行时保留
  • @Documented :描述javadoc
  • @Inherited : 阐述了某个被标注的类型是被继承的

2.注解处理

  • TestProvider注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TestProvider {

    public int id() default -1;
    public String name() default "";
    public String address() default "";
}
  • Apple
public class Apple {
    @TestProvider(id = 1,name = "lwx",address = "aaa")
    private String testProvider;

    public String getTestProvider() {
        return testProvider;
    }

    public void setTestProvider(String testProvider) {
        this.testProvider = testProvider;
    }
}
  • Util
public class Util {
    public static void getTest(Class<?> clazz){
        String str = "lwx";
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields){
            if (field.isAnnotationPresent(TestProvider.class)){
                TestProvider testProvider = (TestProvider) field.getAnnotation(TestProvider.class);
                str = testProvider.id() + testProvider.name();
                System.out.println(str);
            }
        }
    }

    public static void main(String[] args) {
        Util.getTest(Apple.class);
    }
}

3.使用

  • 数组属性
public @interface MyTest{
  String[] value
}

@MyTest({"str","str1"})
posted @ 2023-08-22 13:21  lwx_R  阅读(4)  评论(0编辑  收藏  举报