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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| package com.redisc;
import java.lang.annotation.*; import java.lang.reflect.*; import java.util.List; import java.util.Map;
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @interface Table { String value(); }
@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @interface TableField { String columnName();
String type();
int length(); }
@Table("student") class Student { @TableField(columnName = "id", type = "int", length = 10) public int id; @TableField(columnName = "name", type = "varchar", length = 255) public String name; }
public class Test {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Class c1 = Class.forName("com.redisc.Student");
Annotation[] annotations = c1.getAnnotations(); for (Annotation annotation : annotations) { System.out.println(annotation); }
Table annotation = (Table) c1.getAnnotation(Table.class); System.out.println(annotation.value());
Field f = c1.getDeclaredField("name"); TableField tableField = f.getAnnotation(TableField.class); System.out.println(tableField.columnName()); System.out.println(tableField.type());
} }
|