注解:从JDK5开始,Java增加对元数据的支持,也就是注解,注解与注释是有一定区别的,可以把注解理解为代码里的特殊标记,这些标记可以在编译,类加载,运行时被读取,并执行相应的处理。通过注解开发人员可以在不改变原有代码和逻辑的情况下在源代码中嵌入补充信息。
上面是注解的定义,而直白的说注解其实就相当于标记,我们可以在编译时,类加载时,或者运行时拿到标记,在标记的位置做一些操作。
创建一个注解:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String value();
}
可以看到和普通Java类相似,只不过类是class修饰,而注解是@interface修饰。
而@Target、@Retention是什么意思呢?
这些是元注解,就是注解的注解的意思,这些元注解主要是给注解进行一些配置。
@Target 是用来标记这个注解应该是哪种 Java 成员,就是被修饰的注解可以使用的范围。
ElementType.TYPE 类、接口、注解或枚举声明
ElementType.FIELD 字段声明(包括枚举常量)
ElementType.METHOD 方法声明
ElementType.PARAMETER 形式参数(方法参数)声明
ElementType.CONSTRUCTOR 构造函数声明
ElementType.LOCAL_VARIABLE 局部变量声明
ElementType.ANNOTATION_TYPE 注解声明 (所以元注解肯定都是这个类型的)
ElementType.PACKAGE 包声明
下面两个 jdk1.8之后开始支持
ElementType.TYPE_PARAMETER 类型参数声明
ElementType.TYPE_USE 类型使用
@Retention 指示该注解要保留多长时间,默认为 RetentionPolicy.CLASS类型。
RetentionPolicy.SOURCE 在源文件中有效
RetentionPolicy.CLASS 在class文件中有效
RetentionPolicy.RUNTIME 在运行时有效
@Documented 指示带有该注解的元素将由javadoc记录
@Inherited 是继承的意思 如果被这个修饰的注解 使用该注解的类的子类也被改注解修饰。
以上就是常用的几个元注解。
然后注解里面是没有方法的,只有成员变量,下面是成员变量使用方法。
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String value();
}
@MyAnnotation("test")
public void test(View view) {
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.CLASS)
public @interface MyAnnotation {
int a() default 1;
String value() default "test";
}
@MyAnnotation(a = 2, value = "test")
public void test(View view) {
}
接着我们看一下利用反射获取注解相关属性等操作。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
int a() default 1;
String value() default "test";
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyMethodAnnotation {
String value() default "method";
}
@MyAnnotation(a = 2, value = "test")
public class Test {
@MyMethodAnnotation("method")
public void test() {
}
}
//获取类注解
Class<Test> testClass = Test.class;
boolean isAnnotation = testClass.isAnnotationPresent(MyAnnotation.class);
if(isAnnotation){
BehaviorTrace annotation = testClass.getAnnotation(MyAnnotation.class);
int a = annotation.a();
String value = annotation.value();
}
//获取方法注解
try {
Method test = testClass.getDeclaredMethod("test");
boolean annotationPresent = test.isAnnotationPresent(MyMethodAnnotation.class);
if(annotationPresent){
BehaviorTrace annotation = test.getAnnotation(MyMethodAnnotation.class);
String value = annotation.value();
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
以上这些就是注解的一些基本知识,在真实的开发中多使用一下,熟练一些理解会更深。
在开发中我们使用的一些比如:数据库框架中自动生成SQL语句的框架、AOP面向切面编程等等中都是用到了注解,我们可以在一些需要编译时生成代码,运行时提取信息,用户行为统计等等地方都可以使用注解。