• 自定义注解知识点总结


    Annotation是从java1.5开始引入的版本,类似于枚举类都是继承java.lang.Enum抽象类,java的注解都是隐含的自动继承java.lang.annotation.Annotation接口,由编译程序自动为您完成其它细节,而但我们手动写了一个接口,并让接口继承java.lang.annotation.Annotation接口,那么我们定义的接口不是注解而是接口。注解都继承annotation接口,但是继承该接口并不一定都是注解可能是其他的子接口),另外,在定义注解时,不能继承其它的注解或是接口,Java注解包括内置注解自定义注解

    内置注解:Override、Deprecated、SafeVarargs、SuppressWarnings等

    自定义注解:是利用@Target和@Retention元注解来标志的注解

    public @interface DBTable {
    }
    等价于

    @Target({ElementType所有的枚举类数组})
    @Retention(RetentionPolicy.CLASS)
    public @interface DBTable {
    }
     
    public enum RetentionPolicy {
    /**
    * Annotations are to be discarded by the compiler.
    */
    SOURCE,//编译阶段处理完对应的Annotation就结束,不存在class字节码中

    /**
    * Annotations are to be recorded in the class file by the compiler
    * but need not be retained by the VM at run time. This is the default
    * behavior.
    */
    CLASS,//存在class字节码中,runtime invisible annotation,jvm运行时无法读入,缺省

    /**
    * Annotations are to be recorded in the class file by the compiler and
    * retained by the VM at run time, so they may be read reflectively.
    *
    * @see java.lang.reflect.AnnotatedElement
    */
    RUNTIME //存在class字节码中,运行时可由jvm读入
    }
    public enum ElementType {
    /** Class, interface (including annotation type), or enum declaration */
    TYPE,

    /** Field declaration (includes enum constants) */
    FIELD,

    /** Method declaration */
    METHOD,

    /** Formal parameter declaration */
    PARAMETER,

    /** Constructor declaration */
    CONSTRUCTOR,

    /** Local variable declaration */
    LOCAL_VARIABLE,

    /** Annotation type declaration */
    ANNOTATION_TYPE,

    /** Package declaration */
    PACKAGE,

    /**
    * Type parameter declaration
    *
    * @since 1.8
    */
    TYPE_PARAMETER,

    /**
    * Use of a type
    *
    * @since 1.8
    */
    TYPE_USE
    }

    自定义注解:

    
    
    @Target(ElementType.TYPE) //作用域
    @Retention(RetentionPolicy.RUNTIME) //生命周期
    public @interface DBTable {
        String value() default "master"; //注解属性,约定都是后面跟一对括号,可能jvm虚拟机无法识别到底是final常量值还是注解属性
        DBEnum[] value2();
    }
     
    1、当属性名为value时,在对其赋值时可以不指定属性的名称而直接写上属性值,除了value()以外的其他属性名都要使用name=value显示赋值
    2、属性默认值 用default关键字设置
    3、如何解析在不同作用域的注解,可以使用Class、Constructor、Method、Field、Package提供的接口,因为他们都实现了AnnotatedElement接口。
    4、预设中的父类的自定义的注解DBTable并不会被继承至子类中,除非在DBTable里上@Inherited的注解。(@Inherited更详细的介绍:https://www.jianshu.com/p/7f54e7250be3)
     
  • 相关阅读:
    2013.10.21—2013.10.25周总结
    2013.10.14—2013.10.18周总结
    2013.10.8—2013.10.12周总结
    MongoDb的“not master and slaveok=false”错误及解决方法,读写分离
    python 获取当前时间
    git命令与github使用
    s​s​h​配​置​公​钥​和​私​钥​登​陆​S​e​c​u​r​e​C​R​T
    关于pydev的语法的错误提示
    lnmp1.0 升级php.5.4.28 后出错 Nginx 502 Bad Gateway
    python线程Example
  • 原文地址:https://www.cnblogs.com/feibazhf/p/14354867.html
Copyright © 2020-2023  润新知