在开发中,我们总会和注解打交道,特别是我们用到Spring开发框架的时候,会遇到许许多多的注解;那么注解到底是个什么,我们(像我这样的小白)并不一定了解,那么这次,我们就来揭开注解的神秘面纱:
1: 首先我们来创建一个注解:
package anno;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*@description TODO 自定义注解:
*
* 注:
* 当注解创建出来,自动实现Annotation接口;
* 当注解的属性值为value时,对其定义可以不指定属性名,否则必须指定属性名;
*
* 非标识型注解(注解内有值)只有在反射调用的时候才有意义;
*
* @Target : 声明该注释作用在那种类型上(数组);
*
* @Retention : 做用在注解上的注解,声明注解策略:
* RetentionPolicy : 注解策略:
* SOURCE : JVM丢弃的注解,没有效果;
* CLASS : 将注解编译,但运行时不用;
* RUNTIME: 运行时可用,可以反射性的读取;
*
*@date 2018年1月1日
*@author geYang
**/
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String value();
/*Class<?>[] clazz();
HttpMethod hm();*/
}
从注释中,我们可以知道: 非标识型注解(注解内有值)只有在反射调用的时候才有意义;
注解本身是没有意义的,只有在反射调用的时候才有意义; 那么下面我们就来测试一下,注解的意义:
package test;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import anno.MyAnnotation;
public class MyTest {
/**
* @Deprecated : 声明这个方法不建议被使用;
* @SuppressWarnings : 压制警告的注解:
* unused : 不检查操作的警告;
* rawtypes : 定义时压制泛型的警告;
* */
@Test
@Deprecated
@SuppressWarnings({ "rawtypes", "unused" })
public void test(){
System.out.println("test");
List list = new ArrayList();
}
@MyAnnotation("两整数相加的结果")
private int add(int a,int b){
return a + b;
}
@Test
public void annTest(){
//利用反射来读取注释
Class<? extends MyTest> class1 = this.getClass();
try {
MyTest myTest = class1.newInstance();
Method method = class1.getDeclaredMethod("add", new Class[]{int.class,int.class});
//判断该方法上是否有 @MyAnnotation
boolean b = method.isAnnotationPresent(MyAnnotation.class);
if(b){
//拿到该注解对象:
MyAnnotation myAnnotation = method.getDeclaredAnnotation(MyAnnotation.class);
//获取该注解中的值:
String value = myAnnotation.value();
//反射调用方法:
Object invoke = method.invoke(myTest, new Object[]{5,10});
System.out.println(value+invoke);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
到这里,我们了解了注解的反射调用;那么我们就可以理解开发框架中为什么会有那么多的注解,不管是SpringMVC,SpringBoot...等等,他们的搭建基础 无非就是 注解,反射,动态代理, 经过精心巧妙的封装,为我们开发项目就节省了大量的时间,有了这些基础,我想我们就可以研究一下Spring框架的运行机制啦;
热爱技术,热爱分享......
参考: https://ke.qq.com/course/180327