CLASS |
編譯器將註解記錄在類文件中,但在運行時VM不須要保留註解。默認是此策略。 |
RUNTIME | 編譯器將註解記錄在類文件中,在運行時VM中保留,所以能夠經過反射讀取。 |
SOURCE | 編譯器會丟棄。 |
3. 自定義註解實例 java
註解的定義: 工具
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface UColumn { public int precision() default 8; public int length() default 255; public String name() default ""; }
public class Student { @UColumn(name="id",precision=5) private Integer id; @UColumn(name="name",length=64) private String name; @UColumn(name="age",precision=3) private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
public static void main(String[] args) throws Exception{ Student stu=new Student(); stu.setId(123456); stu.setName("stack"); stu.setAge(1000); Class<?> clazz=stu.getClass(); Field[] fields=clazz.getDeclaredFields(); if(fields.length>0){ for(Field field:fields){ Annotation[] annotations=field.getAnnotations(); if(annotations.length<=0)continue; Class<?> type=field.getType(); for(Annotation annotation:annotations){ if(annotation.annotationType().equals(UColumn.class)){ UColumn col=field.getAnnotation(UColumn.class); if(type.equals(String.class)){ int length=col.length(); if(field.get(stu).toString().length()>length){ System.out.println(field.getName()+" length error!"); } }else if(type.equals(Integer.class)){ int precision=col.precision(); if(field.get(stu).toString().length()>precision){ System.out.println(field.getName()+" length error!"); } } } } } } }