反射5 - 获取注解信息
反射 获取注解信息
什么是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(); //数据长度限制
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析