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();
}
}
}
原文:https://www.cnblogs.com/cqzy/p/10924011.html