package cn.JAVandReflection.AnnotationTest;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
/**
* 本文介绍如何用反射操作注解,以及通过这种方式大致了解ORM获取字段名的方式
* 先定义几个注解,注意观察注解的参数,以及使用时候给参数赋值的名字
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Table {
String value();
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Field1 {
String columnName();
String type();
int length();
}
// 现在定义一个类使用注解
@Table("db_student")
class Student {
@Field1(columnName = "name", type = "varchar", length = 10)
String name;
@Field1(columnName = "age", type = "int", length = 4)
int age;
/*
定义了上面这样的变量,他们都被注解, 用下面的类来通过反射获取注解
*/
}
public class AnnotationConnReflection {
public static void main(String[] args) {
// 通过反射获取注解
// 还是首先获取Class对象
Class c1 = Student.class;
// 获取注解的value值
Annotation annotation = c1.getAnnotation(Table.class);
System.out.println(((Table) annotation).value());
// print : db_student
// 获取字段的
// 首先要获取字段
Field[] declaredFields = c1.getDeclaredFields();
for (Field declaredField : declaredFields) {
Field1 annotation1 = declaredField.getAnnotation(Field1.class);
System.out.println("字段名:" + annotation1.columnName() + "类型:" + annotation1.type() + "长度:" + annotation1.length());
}
/**
* print
* 字段名:name类型:varchar长度:10
* 字段名:age类型:int长度:4
*/
// 通过这种获取注解的方式,可以知道用户定义的类型
}
}