Java通过反射获取注解以及注解中的信息

首先自定义两个注解:
1、用于描述表名,只能用在类、接口、枚举上

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TableName {
    String value();
}

2、用于描述列的信息,列名、数据类型、长度

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ColumnInfo {
    String columnName();
    String type();
    int length();
}

创建实体类

//表名为PersonTable
@TableName("PersonTable")
public class Person {

//设置三个字段的相关信息
    @ColumnInfo(columnName = "姓名",type = "varchar",length = 20)
    private String name;
    @ColumnInfo(columnName = "身份证号",type = "int",length = 5)
    private int id;
    @ColumnInfo(columnName = "年龄",type = "int",length = 3)
    private int age;
}

获取类上的注解,以及注解中的值:

Class person= Person.class;
//直接通过动态类的对象获取类上的注解
Annotation[] annotations = person.getAnnotations();
for (Annotation annotation : annotations) {
    System.out.println(annotation);
}
//获取注解中的值,注解也有Class类的对象
TableName declaredAnnotation = (TableName) person.getDeclaredAnnotation(TableName.class);
//获取注解中的值
System.out.println(declaredAnnotation.value());

在这里插入图片描述
获取类中属性上的注解,以及注解中的值:

Class person= Person.class;
1、获取指定的属性 
Field name = person.getDeclaredField("name");
2、通过getAnnotation方法获取该属性上指定的注解,注意给的参数
ColumnInfo annotation = name.getAnnotation(ColumnInfo.class);
3、获取注解中的值
System.out.print(annotation.columnName()+"  ");
System.out.print(annotation.type()+"  ");
System.out.print(annotation.length());

在这里插入图片描述
通过注解(保存数据库中列的信息)加上反射(解析注解中的信息)我们能获取数据库中列的信息,通过拼接成SQL语句就能够对数据库进行相关操作


版权声明:本文为qq_45800640原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。