java中的Annotation在定义的时候,通常会写以下代码java
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.TYPE)
public @interface Slf4j {
/**
* Sets the category of the constructed Logger. By default, it will use the type where the annotation is placed.
*/
String topic() default "";
}
复制代码
其中会用到以下几个注解 android
主要有以下:程序员
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
/**
* Returns an array of the kinds of elements an annotation type
* can be applied to.
* @return an array of the kinds of elements an annotation type
* can be applied to
*/
ElementType[] value();
}
复制代码
ElementType内容以下:bash
取值 | 描述 |
---|---|
ANNOTATION_TYPE | 应用于注解类型 |
CONSTRUCTOR | 用于构造函数 |
FIELD | 用于字段或属性 |
LOCAL_VARIABLE | 局部变量上使用 |
METHOD | 方法上注释 |
PACKAGE | 用于包的声明上 |
PARAMETER | 做用于方法参数上 |
TYPE | 用于类的任何元素 |
==由于@Target是使用在Annotation上的,因此他的@Target(ElementType.ANNOTATION_TYPE)==app
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
/**
* Returns the retention policy.
* @return the retention policy
*/
RetentionPolicy value();
}
复制代码
RetentionPolicy取值以下:函数
取值 | 描述 |
---|---|
SOURCE | 只做用于编译阶段,而且会被编译器丢弃 |
CLASS | 在编译后会被放进class文件,可是在虚拟机运行期无效(==默认值==) |
RUNTIME | 编译后会被放进class文件,在运行期间有效 |
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.TYPE)
public @interface Slf4j {
/**
* Sets the category of the constructed Logger. By default, it will use the type where the annotation is placed.
*/
String topic() default "";
}
复制代码
lombok.extern.slf4j下的@slf4j注解,是在编译器自动生成代码。因此在运行期间是没有做用的,因此能够写成RetentionPolicy.SOURCE,生成class文件能够将其丢弃。ui
对于服务端程序员来讲,代码编译成class文件,后面就是去运行,处于运行期了,因此注解若是只是在class文件中,会被虚拟机忽略的话,和没进class有什么区别呢??
网上查的资料以下: 首先咱们知道android从源码到apk文件的大致流程: Java源码 —> Class文件 —> Dex文件 —> apk
因此在安卓程序的开发过程当中,写进Class文件的注解能够在class文件->app过程当中起做用spa
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Documented {
}
复制代码
默认状况下,生成javedoc文件的时候,Annotation是不包含在javadoc中的,加上@Documented以后,这个annotation能够出如今javadoc中code
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Inherited {
}
复制代码
Inherited的中文意思就是 遗传的
因此@Inherited的做用是,若是父类中标注了由@Inherited修饰的注解时,子类能够从父类中==遗传==这个注解cdn
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Repeatable {
/**
* Indicates the <em>containing annotation type</em> for the
* repeatable annotation type.
* @return the containing annotation type
*/
Class<? extends Annotation> value();
}
复制代码
上述的几个注解都是在1.5的时候就有了,@Repeatable比较年轻,是在1.8的时候才引入的,做用是能够在一个位置可使用屡次@Repeatable修饰的注解 实例:
@Repeatable(value = Repeats.class)
public @interface Repeat {
String value();
}
public class RepeatDemo {
@Repeat(value = "tag")
@Repeat(value = "tag2")
public void method() {
}
}
复制代码