注解是Java开发中比较常用的一项技能,本篇文章将结合注解与反射这2块知识点进行讲解,为后续的自定义实现ORM框架做铺垫。关于Java反射的文章可以见本篇文章:Java反射
注解的定义
- JDK5引入的新特性;在引入这个新特性之后,就被大量的框架所采用,在Spring中应用的及其广泛
- 注解可以大大提升编码效率以及代码的精简
比如:@Override @Deprecated @SuppressWarnings
- 注解可以使用在package/Class/Field/Method上
问题: 注解如何进行定义呢?
可以通过@interface关键字进行定义,如下:
/**
* 该注解用于将数据存储到MySQL
*
* 表示该annotation可以定义在类上
* 表示该annotation在运行时会被加载到
*
* @Author: huhu
* @Date: 2019-07-21 16:18
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface HuHuBean {
// 注解中的属性叫做成员变量
String table();
String from() default "huhu";
}
其中:
- @Target:表示该注解用于什么地方
- @Retention:表示注解传递存活时间
/**
* @Author: huhu
* @Date: 2019-07-21 16:33
*/
@HuHuBean(table = "t_animal")
public class Animal {
private Integer id;
private String name;
private String sex;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
注意:如果from成员变量没有设置默认值的话,在使用@HuHuBean的时候会需要我们必须设置from的默认值
注解之通过反射获取注解的信息
@Test
public void test01() throws Exception {
Class<?> clazz = Class.forName("com.zhaotao.annotation.Animal");
// 判断该Class上是否有指定的注解出现
boolean isAnnotation = clazz.isAnnotationPresent(HuHuBean.class);
System.out.println(isAnnotation);
if (isAnnotation) {
HuHuBean huHuBean = clazz.getAnnotation(HuHuBean.class);
if (huHuBean != null) {
System.out.println(huHuBean);
System.out.println(huHuBean.table() + " : " + huHuBean.from());
}
}
}
运行结果:
注解之字段注解定义及获取
上述内容中已经完成了对定义类的注解的开发,这里开发一个定义在字段上的注解:
/**
* 该注解仅限使用在Field上
*
* @Author: huhu
* @Date: 2019-07-21 17:03
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface HuHuField {
String value();
}
同时对应的修改Animal类中的sex字段,定义一个新的名称:
@HuHuField("gender")
private String sex;
字段注解中相关信息的获取:
@Test
public void test02() throws Exception {
Class<?> clazz = Class.forName("com.zhaotao.annotation.Animal");
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
HuHuField huHuField = field.getAnnotation(HuHuField.class);
if (huHuField != null) {
/**
* Bean id
* MySQL id_xxx
* 需要能够将2者对应起来,因此会需要用到HuHuField这种定义在字段上的注解
*/
System.out.println(field.getName() + " : " + huHuField.value());
}
}
}
运行结果:
定义一个HuHuField的注解意义在于:将JavaBean中的字段给映射到MySQL的字段上面去,因为有时候会有这种场景存在,比如bean中的字段名与mysql中的字段名有不一致的情况,因此会有类似的需求,需要我们这样去操作