Java 自定義註解

  1. Java經過關鍵字@interface實現自定義註解
  2. Java經過元註解來約束其它註解。元註解即註解的註解。元註解包括四個:
  • @Target.指示註解類型所適用的程序元素的種類。
  • @Retention.指示註解類型的註解要保留多久。RetentionPolicy包含3個值:
            
CLASS
編譯器將註解記錄在類文件中,但在運行時VM不須要保留註解。默認是此策略。
RUNTIME 編譯器將註解記錄在類文件中,在運行時VM中保留,所以能夠經過反射讀取。
SOURCE 編譯器會丟棄。
  • @Documented.指示某一類型的註解將經過javadoc和相似的默認工具進行文檔化。
  • @Inherited.指示該註解類型將被繼承。

    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!");
							}
						}
					}
						
				}
					
			}
		}
	}
相關文章
相關標籤/搜索