用注解来校验数据的有效性

@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));
	}
}

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