Java:自定义注解与反射

1. 简单介绍

  • 作用:不是程序本身,是作为类似注释的方式对程序作出解释,也存在检查和约束作用
  • 格式:使用**@注解名(参数)**格式
  • 使用地点:可以在包、类、字段和方法上使用

2. 元注解

用来解释注解的注解,Java中定义了4个标准的元注解
@Target 描述注解使用范围
@Retention 表示需要在什么级别保存该注解信息,描述生命周期
@Document 说明将该注解包含在javadoc中
@Inherited 说明子类可以继承父类中的该注解

3. 自定义注解

// METHOD:可以定义在方法上, TYPE:可以定义在类上
@Target(value = {ElementType.METHOD, ElementType.TYPE})
// RUNTIME:运行时级别,这里没有指定value = 是因为参数名为value并只有一个参数时可忽略
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
    // 该参数指定了默认值为hello,表名不指定该参数时默认为hello
    String value() default "hello";
    // 该参数为必填项,并且可以使用{"a", "b"}的方式传入多个参数
    String[] message();
}

// 该注解声明只作用在字段上
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldAnnotation{
    String value();
}

4. 使用注解

@MyAnnotation(message = {"hello", "world"})
class AnnotationDemo {

    @FieldAnnotation("String name annotation")
    private String name;

    @FieldAnnotation("int age annotation")
    private int age;

    // ... 省略构造器和get/set
}

5. 测试

	public static void main(String[] args) throws ClassNotFoundException {
        Class<?> clazz = Class.forName("com.demo.AnnotationDemo");
        // 获取该类上所有的注解类型
        Annotation[] annotations = clazz.getAnnotations();
        // 遍历类上注解
        for (Annotation annotation : annotations) {
            Class<? extends Annotation> annotationType = annotation.annotationType();
            // 判断类上注解类型
            Annotation annotation1 = clazz.getAnnotation(annotationType);
            if (annotation1 instanceof MyAnnotation) {
                MyAnnotation myAnnotation = (MyAnnotation) annotation1;
                // 获取注解信息
                String[] message = myAnnotation.message();
                String value = myAnnotation.value();
            }
        }

        // 获取该类所有字段
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            FieldAnnotation annotation = field.getAnnotation(FieldAnnotation.class);
            // 获取字段上注解的值
            String value = annotation.value();
        }

        // 获取方法上的注解类似
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            //method.getAnnotation()
        }

    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值