自定义注解知识点总结

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)

 

 
posted @ 2021-02-01 01:10  feibazhf  阅读(87)  评论(0编辑  收藏  举报