注解学习笔记之自定义注解
@Target({1,2,3,4,5,6,7})
- 1.ElementType.CONSTRUCTOR:用于描述构造器
- 2.ElementType.FIELD:用于描述域
- 3.ElementType.LOCAL_VARIABLE:用于描述局部变量
- 4.ElementType.METHOD:用于描述方法
- 5.ElementType.PACKAGE:用于描述包
- 6.ElementType.PARAMETER:用于描述参数
- 7.ElementType.TYPE:用于描述类、接口(包括注解类型) 或enum声明
@Retention(1/2/3)
- 1.RetentionPolicy.SOURCE:注解只保留在源文件,当Java文件编译成class文件的时候,注解被遗弃;
- 2.RetentionPolicy.CLASS:注解被保留到class文件,但jvm加载class文件时候被遗弃,这是默认的生命周期;
- 3.RetentionPolicy.RUNTIME:注解不仅被保存到class文件中,jvm加载class文件之后,仍然存在;
自定义注解的练习代码
SxtTable
- 类和表的对应注解
/**
* 自定义一个类和表的对应注解
*/
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)//指明此注解用于注解类
@Retention(RetentionPolicy.RUNTIME)//指明注解不仅被保存到class文件中,jvm加载class文件之后,仍然存在
public @interface SxtTable {
String value();//值为类对应的表名
}
SxtField
- 属性注解
/**
* 自定义一个属性注解
*/
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SxtField {
String columnName();//表中字段的列名
String type();//字段的类型
int length();//字段的长度
}
SxtStudent
- 学生类
/**
* 创建一个student类并使用自定义的注解
*/
@SxtTable("tb_student")//对类使用注解
public class SxtStudent {
@SxtField(columnName = "id",type ="int",length = 10)//对属性id使用注解
private int id;
@SxtField(columnName = "sname",type ="varchar",length = 10)//对属性studentName使用注解
private String studentName;
@SxtField(columnName = "age",type ="int",length = 4)//对属性age使用注解
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
SxtTest
- 测试类获取注解信息并打印
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
/**
* 使用反射读取注解信息,模拟注解信息处理的流程
*/
public class SxtTest {
public static void main(String[] args) {
try {
Class clazz = Class.forName("com.sxt.SxtStudent");
//获得类所有的注解(这只直接获得所有有效的注解)
Annotation[] annotations = clazz.getAnnotations();
for (Annotation annotation : annotations) {
//打印获取到的注解信息
System.out.println(annotation);
}
//也可以获得指定的注解(获得指定的注解)这里指定的是SxtTable 如果有多个类注解也可以依次指定
SxtTable sxtTable = (SxtTable) clazz.getAnnotation(SxtTable.class);
//打印获取到的注解信息
System.out.println(sxtTable.value());
//获得属性的注解(这里只拿studentName这一个属性来做示例)
Field studentName = clazz.getDeclaredField("studentName");
SxtField sxtField = studentName.getAnnotation(SxtField.class);
//打印获取到的注解信息
System.out.println(sxtField.columnName()+"--"+sxtField.type()+"--"+sxtField.length());
//根据获得的表名,字段信息,可以通过jdbc 执行sql语句在数据库中生成对应的表
//本例用来练习自定义注解故不再往下往下写只对信息进行了打印
} catch (Exception e) {
e.printStackTrace();
}
}
}