利用Java反射机制读取注解
java代码:
package ORM;
@SxtTable("tb_student")
public class SxtStudent {
@SxtField(columnName="id", type="int", length=10)
private int id;
@SxtField(columnName="sname", type="varchar", length=10)
private String studentName;
@SxtField(columnName="age", type = "int", length=3)
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getStudnet() {
return studentName;
}
public void setStudnet(String studnet) {
this.studentName = studnet;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
自定义注解:
package ORM;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.lang.model.element.Element;
@Target(value = ElementType.FIELD) //此注解能用于类 接口 枚举 Annotation类型之前
@Retention(RetentionPolicy.RUNTIME) //表示此注解可以被反射机制读取
public @interface SxtField {
String columnName();
String type();
int length();
}
package ORM;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.lang.model.element.Element;
@Target(value = ElementType.TYPE) //此注解能用于类 接口 枚举 Annotation类型之前
@Retention(RetentionPolicy.RUNTIME) //表示此注解可以被反射机制读取
public @interface SxtTable {
String[] value();
}
通过class获取注解信息:
package ORM;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
/**
* 使用反射读取注解信息,模拟处理注解信息的流程
* @author lenovo
*
*/
public class ORM {
public static void main(String[] args) {
try {
Class clazz = Class.forName("ORM.SxtStudent"); //返回一个反射对象
Annotation[] annotations = clazz.getAnnotations(); //获得类的全部注解即@SxtTable("tb_student")
for(Annotation a: annotations) {
System.out.println(a);
}
//获得类指定的注解
SxtTable st = (SxtTable) clazz.getAnnotation(SxtTable.class);
System.out.println(st.value());
//获得类的属性注解
Field f = clazz.getDeclaredField("studentName");
SxtField sxtField = f.getAnnotation(SxtField.class);
System.out.println(sxtField.columnName() + "--" + sxtField.type() + "--" + sxtField.length());
//根据获得的表名, 字段信息, 拼出DDL语句, 使用JDBC执行SQL语句, 在数据库中生成相关的表
} catch (Exception e) {
e.printStackTrace();
}
}
}
结果:
还没有评论,来说两句吧...