当注解的@Retention为RUNTIME时,此注解为运行时注解。
如果一个元素上面使用了运行时注解,我们可以在运行时使用反射,读取元素上的注解进行解析处理。
比如说对于如下的实体类Student,我们想根据他的成员变量生成插入数据库时的SQL语句
public class Student {
@ColumnAnnotation(columnName = "id", length = 10, type = "int") private int id;
@ColumnAnnotation(columnName = "sname", length = 10, type = "varchar") private String name;
@ColumnAnnotation(columnName = "age", length = 10, type = "int") private int age;
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
} |
则可以创建如下的注解ColumnAnnotation,在Student类上使用注解,在运行时通过解析注解来生成语句
@Target(value={ElementType.FIELD}) @Retention(value = RetentionPolicy.RUNTIME) public @interface ColumnAnnotation {
String columnName(); String type(); int length(); } |
public static void main(String[] args) { try { //获得类 Class<?> clazz = Class.forName("com.bjsxt.annotation.Student");
//获得类的注解 Annotation[] annotations = clazz.getAnnotations(); for (Annotation annotation : annotations) { System.out.println(annotation); }
//获得类的成员变量name Field field = clazz.getDeclaredField("name");
//获得成员变量上的注解 ColumnAnnotation sf = field.getAnnotation(ColumnAnnotation.class); System.out.println(sf.columnName()); System.out.println(sf.type()); System.out.println(sf.length());
} catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } } |