0%
一个ORM例子
定义注解
1 2 3 4 5 6 7 8 9 10 11 12 13
| @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @interface Table { String value(); }
@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @interface Field { String colName(); String type(); int length(); }
|
实体类
1 2 3 4 5 6 7 8 9
| @Table("user") class User { @Field(colName = "user_id", type = "int", length = 10) private int id; @Field(colName = "user_name", type = "varchar", length = 10) private String name; @Field(colName = "user_password", type = "varchar", length = 64) private String password; }
|
获取注解进行处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| public class ReflectAnno { public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException { Class<User> c = User.class;
Annotation[] annotations = c.getAnnotations(); for (Annotation annotation : annotations) { System.out.println("annotation = " + annotation); }
Table target = c.getAnnotation(Table.class); System.out.println(target.value());
java.lang.reflect.Field name = c.getDeclaredField("name"); Field nameAnnotation = name.getAnnotation(Field.class); System.out.println("nameAnnotation.colName() = " + nameAnnotation.colName()); System.out.println("nameAnnotation.type() = " + nameAnnotation.type()); System.out.println("nameAnnotation.length() = " + nameAnnotation.length());
Method setPassword = c.getDeclaredMethod("setPassword", String.class); setPassword.getAnnotations(); } }
|