一、简单使用
1.1、自定义注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public @interface OnClick {
int value();
}
1.2、注解作用位置设置(@Target)
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
*/
//类型变量的声明语句中(如,泛型声明)<@TypeParam T extends Integer>
TYPE_PARAMETER,
/**
* Use of a type
*
* @since 1.8
*/
//可以在任何地方使用
TYPE_USE
}
1.3、注解的保留级设置(@Retention)
public enum RetentionPolicy {
//源代码中保留
SOURCE,
//源代码中,字节码中保留
CLASS,
//源代码中,字节码中,运行时中保留
RUNTIME
}
1.4、保留级对应的使用场景
级别 | 技术 | 说明 |
---|---|---|
source | APT | 在编译期能获取注解及注解声明的类包扩类中的所有成员信息,一般用于生成辅助类信息 |
class | 字节码增强 | 编译出Class后,通过修改Class数据以实现修改代码逻辑的目的。对于是否需要修改的区分或者修改为不同的逻辑的判断可以使用注解 |
runtime | 反射 | 在程序运行期间,通过反射技术动态获取注解与其元素,从而完成不同的逻辑判定 |
source使用场景:ide 语法检查,如:@IntDef
1.6、使用注解限定传参范围
public class AnnotationTest {
private static final int SUNDAY = 1;
private static final int MONDAY = 2;
@WeekDay private static int mCurrentDay;
@IntDef({SUNDAY, MONDAY})
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.SOURCE)
@interface WeekDay {
}
public static void setCurrentDay(@WeekDay int currentDay) {
mCurrentDay = currentDay;
}
public static void main(String[] args) {
setCurrentDay(MONDAY);
setCurrentDay(45); //会报错,因为限定只能传SUNDAY, MONDAY
}
}