反射操作注解
反射操作注解
-
getAnnotations
-
getAnnotation
练习:ORM
-
了解什么是ORM?
-
Object relationship Mapping--> 对象关系映射
-
类和表结构对应
-
属性和字段对应
-
对象和记录对应
-
-
要求:利用注解和反射完成类和表结构的映射关系
package com.hua.reflection; import java.lang.annotation.*; import java.lang.reflect.Field; //练习反射操作注解 public class Test12 { public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException { //通过反射获取注解 Class c1 = Class.forName("com.hua.test08.Cat"); Annotation[] annotations = c1.getAnnotations(); for (Annotation annotation : annotations) { System.out.println(annotation); } //获得注解的value的值 Tablehua tablehua = (Tablehua)c1.getAnnotation(Tablehua.class); String value = tablehua.value(); System.out.println(value); //获得类指定的注解 Field f = c1.getDeclaredField("name"); Fieldhua annotation = f.getAnnotation(Fieldhua.class); System.out.println(annotation.columnName()); System.out.println(annotation.type()); System.out.println(annotation.length()); } } @Tablehua("db_cat") class Cat{ @Fieldhua(columnName = "db_name",type = "varchar",length = 10) private String name; @Fieldhua(columnName = "db_id",type = "int",length = 10) private int id; @Fieldhua(columnName = "db_age",type = "int",length = 10) private int age; public Cat() { } public Cat(String name, int id, int age) { this.name = name; this.id = id; this.age = age; } public String getName() { return name; } public void setName(String name) { 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; } @Override public String toString() { return "Cat{" + "name='" + name + '\'' + ", id=" + id + ", age=" + age + '}'; } } //类名的注解 @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @interface Tablehua{ String value(); } //属性的注解 @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @interface Fieldhua{ String columnName(); String type(); int length(); }