注解

作者: 寂静的春天1988 | 来源:发表于2020-09-02 09:47 被阅读0次

    自定义注解

    public @interface User{
        
        String name() default "";
        
        int age();
    }
    @User(age = 10)
    class Demo{
        
    }
    

    使用注解时,如果属性有默认值可以不用赋值。

    public @interface User{
        
        String name() default "";
        
        String value() default "";
    }
    @User("123")
    class Demo{
        
    }
    

    使用注解时,如果只给value属性赋值可以省略value=

    注解属性的类型

    1、8种基本类型
    2、string
    3、Enum
    4、class
    5、注解类型
    6、以上5种的一维数组

    public @interface User{
        int age();
        
        String name();
        
        MyEnum myEnum();
        
        Class a();
        
        MyAnno no();
        
        String[] arr();
    }
    enum MyEnum{
        A,B,C
    }
    
    @interface MyAnno{
    
        
    }
    @User(age = 10,name = "tom",myEnum = MyEnum.A,a = String.class,no = @MyAnno,arr = {"1","2","3"})
    class Demo{
        
    }
    

    数组类型如果只有一个值可以省略{}

    注解的作用目标限定

    @Target(value = {ElementType.METHOD,ElementType.FIELD})
    public @interface User{
        
    }
    

    使用@Target注解限定注解放的位置。

    保留策略

    • 源代码文件(SOURCE):只在源代码中存在,编译时被忽略
    • 字节码文件(CLASS):在源代码存在,编译时会把注解信息放到class文件,但在JVM加载类时,会忽略注解!
    • JVM中(RUNTIME):注解在源代码、字节码中存在,并在JVM加载类时会把注解加载到内存中(是唯一可以反射的注解!)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface User{
        
    }
    

    使用@Retention注解,限定保留策略

    反射获得注解

    @Retention(RetentionPolicy.RUNTIME)
    public @interface User{
        String name();
    }
    @User(name="tom")
    class Demo{
        @User(name="jack")
        public void demo() {
            
        }
    }
    
        public static void main(String[] args) {
            // 获得作用目标
            Class<Demo> c=Demo.class;
            // 获得注解
            User user=c.getAnnotation(User.class);
            System.out.println(user.name());
            // 获得所有注解
            Annotation[] arr =c.getAnnotations();
        }
    

    上面是获得类的注解,接下来获得方法上的注解

        public static void main(String[] args) throws NoSuchMethodException, SecurityException {
            // 获得作用目标
            Class<Demo> c=Demo.class;
            Method method=c.getMethod("demo");
            // 获得注解
            User user=method.getAnnotation(User.class);
            System.out.println(user.name());
            // 获得所有注解
            Annotation[] arr =c.getAnnotations();
        }
    

    相关文章

      网友评论

          本文标题:注解

          本文链接:https://www.haomeiwen.com/subject/tcxpsktx.html