反射 获取注解信息
什么是ORM?
Object relationship Mapping -- 对象关系映射(数据库关系)
- 类 -> 表
- 类中属性 -> 表的字段
- 类的对象 -> 表中的记录
通过注解联系属性与数据库字段
package annotation;
import java.lang.annotation.*;
import java.lang.reflect.Field;
public class ReflectAnnotation {
public static void main(String[] args) throws NoSuchFieldException {
Class<Student> c1 = Student.class;
//通过反射获得注解
Annotation[] annotations = c1.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation); //@annotation.TableAshen(value=db_student)
}
//获得注解的value的值
TableAshen tableAshen = (TableAshen) c1.getAnnotation(TableAshen.class);
System.out.println(tableAshen.value()); //db_student
//获得类指定的注解 -- 属性name 对应注解的约束内容
Field f = c1.getDeclaredField("name");
FieldAshen annotation = f.getAnnotation(FieldAshen.class);
System.out.println(annotation.columuName());
System.out.println(annotation.type());
System.out.println(annotation.lenth());
}
}
@TableAshen("db_student") //该对应数据库名为db_student
class Student{
//通过注解约束,维持对象属性与数据库字段的一致性
@FieldAshen(columuName = "db_id", type = "int", lenth = 10)
private int id;
@FieldAshen(columuName = "db_age", type = "int", lenth = 10)
private int age;
@FieldAshen(columuName = "db_name", type = "varchar", lenth = 3)
private String name;
public Student() {
}
public Student(int id, int age, String name) {
this.id = id;
this.age = age;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
//自定义注解 -- 约束类名 => 数据库中的表名
@Target(ElementType.TYPE) //作用在类上
@Retention(RetentionPolicy.RUNTIME)
@interface TableAshen{
String value();
}
//自定义注解 -- 约束属性 => 数据库中的字段
@Target(ElementType.FIELD) //作用在属性上
@Retention(RetentionPolicy.RUNTIME)
@interface FieldAshen{
String columuName(); //数据库中列名
String type(); //存储数据类型
int lenth(); //数据长度限制
}
标签:反射,name,int,age,annotation,获取,id,注解,public
From: https://www.cnblogs.com/Ashen-/p/17028155.html