本帖最后由 yandong_mars 于 2012-11-21 15:57:15 编辑 package annotation;
/**
*
* @author Administrator
* 框架支持的数据类型
*/
public enum DataType {
StringType, NumberType, DateType
}
package annotation;
/**
*
* @author Administrator
* 是否做非空验证
*/
public enum NULLABLE {
Yes, No
}
package annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
* @author Administrator
* 验证数据类型的注解
*/
@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Type {
DataType type();
NULLABLE nullAble();
String ex() default "";
int minLength() default 0;
int maxLength() default 2048;
long maxValue() default 99999999999999l;
long minValue() default -99999999999999l;
}
package annotation;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.springframework.beans.BeanUtils;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
/**
*
* @author Administrator
* 验证实现类 这里只实现了整型数据的验证
* main方法写到这里了 测试用的
*/
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
new Test().validate();
}
public void validate() {
Entity entity = new Entity();
entity.setId(3);
if (entity != null) {
Field[] fields = entity.getClass().getDeclaredFields();
for (Field field : fields) {
Type type = (Type) field.getAnnotations()[0];
Method method = ReflectionUtils.findMethod(this.getClass(), type.type().toString(),new Class[]{field.getClass(),Type.class,Object.class});
ReflectionUtils.invokeMethod(method, this, new Object[]{field,type,entity});
}
}
}
public void NumberType(Field field,Type type,Object entity) {
Object tem = getFieldValue(field,entity);
if(NULLABLE.No.equals(type.nullAble())) {
Assert.notNull(tem,entity.getClass()+"."+field.getName()+" 空 ");
long value = new Long(tem.toString());
Assert.isTrue(value <= type.maxValue() && value >= type.minValue(),entity.getClass()+" property {"+field.getName()+"} value "+type.minValue()+"-" + type.maxValue());
} else if(tem != null) {
long value = new Long(tem.toString());
Assert.isTrue(value <= type.maxValue() && value >= type.minValue(),entity.getClass()+" property {"+field.getName()+"} value "+type.minValue()+"-" + type.maxValue());
}
}
public void StringType(Field field,Type type) {