用註解來校驗數據的有效性

@MyValidator
public class Book {
	@MyValidator(min=0,max=10000)
	public int price;
	@MyValidator(isNotNull=true)
	public String bname;
	public Book(int price, String bname) {
		super();
		this.price = price;
		this.bname = bname;
	}
	
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.FIELD})//類,屬性
@interface MyValidator{
	boolean isNotNull() default false;//是否檢查該屬性是否爲空
	int min() default 0;//檢查該屬性的最小值
	int max() default Integer.MAX_VALUE;//檢查該屬性的最大值
}
public class 場景1_對象屬性校驗 {
	//檢查指定的對象是否有問題	,如果有問題,返回false
	static boolean checkObject(Object obj) throws Exception{
		if(obj==null)
			return true;
		 Class c=obj.getClass();
		 if(!c.isAnnotationPresent(MyValidator.class)){//如果這個類上面沒有註釋
			 System.out.println("該對象無需檢查!");
			 return true;
		 }
		//檢查所有屬性
		 Field[] fields=c.getDeclaredFields();
		 for(Field f:fields){
			 //如果不帶註解,就忽視下面的代碼
			 if(!f.isAnnotationPresent(MyValidator.class)){
				 continue;
			 }
			 Object value=f.get(obj);//獲得入參對象該字段的值	
			 MyValidator v=f.getAnnotation(MyValidator.class);//獲得當前對象的註解屬性
			 if(value==null && v.isNotNull()){
				 System.out.println(f.getName()+"不允許爲空!");
				 return false;
			 }
			 if(f.getType().getSimpleName().indexOf("Integer")==0||f.getType().getSimpleName().indexOf("int")==0){
				 if(Integer.compare((Integer)value,v.min())<0){
					 System.out.println("不能比最小值小");
					 return false;
				 }
				 if(Integer.compare((Integer)value,v.max())>0){
					 System.out.println("不能比最大值大");
					 return false;
				 }
			 }
			 
		 }
		return true;
	}
	public static void main(String[] args) throws Exception {
		Book b=new Book(1000,null);
		System.out.println(checkObject(b));
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章