十四、反射操作注解
模拟ORM的类注解和属性注解
//模拟ORM
public class Demo11 {
public static void main(String[] args) {
Class clazz = Role.class;
//获取类的注解信息
Annotation[] classAnnotations = clazz.getAnnotations();
for (Annotation classAnnotation : classAnnotations) {
System.out.println(classAnnotation);
}
//单独打印name的值
Table table = (Table) clazz.getAnnotation(Table.class);
System.out.println(table.name());
System.out.println("==================");
//获取属性的注解信息
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
Annotation[] fieldAnnotations = field.getAnnotations();
for (Annotation fieldAnnotation : fieldAnnotations) {
System.out.println(fieldAnnotation);
}
}
//单独获取
for (Field field : fields) {
Column column = (Column) field.getAnnotation(Column.class);
System.out.println("name="+column.name()+",type="+column.type()+",length="+column.length());;
}
}
}
@Table(name = "user")
class Role {
@Column(name = "id",type = "int",length = 10)
Integer id;
@Column(name = "name",type = "char",length = 255)
String name;
@Column(name = "type",type = "char",length = 2)
String type;
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@interface Table {
String name();
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@interface Column {
String name();
String type();
int length();
}