Java注解的创建与属性的获取

注解

作用

注解常见的作用有以下几种

  1. 生成文档。这是最常见的

  2. 跟踪代码依赖性,实现替代配置文件功能。

  3. 在编译时进行格式检查。

元注解

元注解负责解释其它注解

  • @Target:用于描述注解的使用范围(即:被描述的注解可以用在什么地方)
    • ElemenetType.CONSTRUCTOR------------------------ 构造器声明
    • ElemenetType.FIELD -------------------------------------- 域声明(包括 enum 实例)
    • ElemenetType.LOCAL_VARIABLE---------------------- 局部变量声明
    • ElemenetType.METHOD --------------------------------- 方法声明
    • ElemenetType.PACKAGE --------------------------------- 包声明
    • ElemenetType.PARAMETER ----------------------------- 参数声明
    • ElemenetType.TYPE---------------------------------------- 类,接口(包括注解类型)或enum声明
  • @Retention :表示需要在什么级别保存该注释信息,用于描述注解的生命周期
    • (SOURCE < CL ASS < RUNTIME)
  • @Document: 说明该注解将被包含在javadoc中
  • @Inherited: 说明子类可以继承父类中的该注解
新建注解并简单应用
  1. 新建注解

    //元注解
    @Target({ElementType.TYPE,ElementType.METHOD,ElementType.FIELD})        //用来表示注解的作用范围这里可以用在 类型,方法,属性变量上
    @Retention(RetentionPolicy.RUNTIME)                                     //设置注解的生命周期
    @Inherited                                                              //表示可以被子类继承
    //通过 @interface建立一个我们的注解
    @interface MyAnnotation {
        //注解的属性需要以 () 结尾,如果没有设置默认值那么在使用标签的时候需要为它赋值
        String name();          //注解的属性name,字符串属性
    
        int id() default 0;     //为属性id添加一个默认值0
    }
    
  2. 新建Test类

    @MyAnnotation(name = "TestType",id=1)       //注解用在类型上
    class Test {
        @MyAnnotation(name = "TestField")           //注解用在属性上
        public String mmm = "This is a test example!";
    
        @MyAnnotation(name = "TestMethod")           //注解用在方法上
        public void print() {
            System.out.println(mmm);
        }
    }
    
  3. 新建测试方法

    public class TestMain {
        public static void main(String[] args) throws ClassNotFoundException {
            //获取Test类的Class对象,以便于通过反射构建该类的实例
            Class clazz = Class.forName("by.test.Test");
    
            //获取对该类的注解
            Annotation[] annotations = clazz.getAnnotations();
            for (Annotation annotation : annotations) {
                MyAnnotation myAnnotation = (MyAnnotation) annotation;    //通过强制转换将Annotation类型转换为我们所定义的注解类型以便于操作
                System.out.println("id=" + myAnnotation.id() + ",name=" + myAnnotation.name());
            }
    
            System.out.println("=========分割线==========");
    
            //获取方法注解
            Method[] methods = clazz.getDeclaredMethods();
            for (Method method : methods) {
                //判断是否存在方法注解
                if (method.isAnnotationPresent(MyAnnotation.class)) {
                    MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);  //在该方法中获取注解
                    System.out.println("id=" + myAnnotation.id() + ",name=" + myAnnotation.name());
                }
            }
        }
    }
    
  4. 最终代码

    package by.test;
    
    import java.lang.annotation.*;
    import java.lang.reflect.Method;
    
    /**
     * @author 
     * @version 1.0
     * @date 2021/12/17 16:29
     */
    
    
    public class TestMain {
        public static void main(String[] args) throws ClassNotFoundException {
            //获取Test类的Class对象,以便于通过反射构建该类的实例
            Class clazz = Class.forName("by.test.Test");
    
            //获取对该类的注解
            Annotation[] annotations = clazz.getAnnotations();
            for (Annotation annotation : annotations) {
                MyAnnotation myAnnotation = (MyAnnotation) annotation;    //通过强制转换将Annotation类型转换为我们所定义的注解类型以便于操作
                System.out.println("id=" + myAnnotation.id() + ",name=" + myAnnotation.name());
            }
    
            System.out.println("=========分割线==========");
    
            //获取方法注解
            Method[] methods = clazz.getDeclaredMethods();
            for (Method method : methods) {
                //判断是否存在方法注解
                if (method.isAnnotationPresent(MyAnnotation.class)) {
                    MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);  //在该方法中获取注解
                    System.out.println("id=" + myAnnotation.id() + ",name=" + myAnnotation.name());
                }
            }
        }
    }
    
    @MyAnnotation(name = "TestType",id=1)       //注解用在类型上
    class Test {
        @MyAnnotation(name = "TestField")           //注解用在属性上
        public String mmm = "This is a test example!";
    
        @MyAnnotation(name = "TestMethod")           //注解用在方法上
        public void print() {
            System.out.println(mmm);
        }
    }
    
    //元注解
    @Target({ElementType.TYPE,ElementType.METHOD,ElementType.FIELD})        //用来表示注解的作用范围这里可以用在 类型,方法,属性变量上
    @Retention(RetentionPolicy.RUNTIME)                                     //设置注解的生命周期
    @Inherited                                                              //表示可以被子类继承
    //通过 @interface建立一个我们的注解
    @interface MyAnnotation {
        //注解的属性需要以 () 结尾,如果没有设置默认值那么在使用标签的时候需要为它赋值
        String name();          //注解的属性name,字符串属性
    
        int id() default 0;     //为属性id添加一个默认值0
    }
    

    运行结果:

    id=1,name=TestType
    =========分割线==========
    id=0,name=TestMethod
    

    这里只是简单的介绍了一下注解的创建以及如何获取注解内的属性,其它更深层次的运用,目前由于本人水平有限还不太了解。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Java的反射机制来动态给属性加上注解,具体步骤如下: 1. 获取需要添加注解属性对应的Field对象,可以使用Class类的getField()或getDeclaredField()方法获取。 2. 获取对应的注解类,可以使用Class类的getAnnotation()方法获取。 3. 使用Java反射机制创建一个AnnotationInvocationHandler对象,并将需要添加注解属性注解类传递给该对象。 4. 使用Java动态代理机制生成一个代理对象,该代理对象实现了注解类对应的口。 5. 将生成的代理对象通过反射设置到属性上,可以使用Field类的setAnnotation()方法。 以下是一个示例代码: ```java // 获取需要添加注解属性 Field field = MyClass.class.getDeclaredField("myField"); // 获取注解类 MyAnnotation annotation = MyAnnotation.class.getAnnotation(MyAnnotation.class); // 创建AnnotationInvocationHandler对象 AnnotationInvocationHandler handler = new AnnotationInvocationHandler(annotation, field); // 使用Java动态代理机制生成代理对象 MyAnnotation proxyAnnotation = (MyAnnotation) Proxy.newProxyInstance( MyAnnotation.class.getClassLoader(), new Class<?>[] { MyAnnotation.class }, handler); // 将生成的代理对象设置到属性上 field.setAnnotation(proxyAnnotation); ``` 其中,AnnotationInvocationHandler类的实现可以参考下面的示例代码: ```java public class AnnotationInvocationHandler implements InvocationHandler { private final Object annotation; private final Field field; public AnnotationInvocationHandler(Object annotation, Field field) { this.annotation = annotation; this.field = field; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // 如果调用的方法是annotationType(),则返回注解类的Class对象 if (method.getName().equals("annotationType")) { return annotation.getClass(); } // 否则调用注解对象的对应方法 return method.invoke(annotation, args); } } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值