您的位置:首页 > 其它

使用自定义注解来验证属性是否规范

2016-08-23 14:33 459 查看
上一篇文章我们写了一个通过注解返回查询sql语句的例子,这次我们来使用注解去验证某个对象属性是否按照我们的注解来赋值的。

例子:我们需要定义一个MyLimit的注解,这个注解里面规定了类属性的限制;编写注解解析;在类中属性使用注解;最后测试是否是我们需要的效果。

定义MyLimit注解:

@Target({ ElementType.FIELD })
// 标注只能放在类或接口的注解
@Retention(RetentionPolicy.RUNTIME)
// 在运行时有效
public @interface MyLimit {
//这个字段是否为必填
boolean isNotNull() default false;
// 字段描述
String description() default "";
int MaxLength() default 0;
int MinLength() default 0;
//表示这个字段是否为int类型
boolean isInt() default false;
int MaxNum() default 30;
int MinNum() default 18;
}编写注解的解析:VerifyAnnotationMyLimit类,这个里面使用一个List来存放验证的错误信息,getListExceptions()方法返回这个List,可以通过annotationMyLimit.getListExceptions().size()!=0来判断验证是否成功,不成功可以取得错误信息:
VerifyAnnotationMyLimit:import java.lang.reflect.Field;
import java.util.ArrayList;

public class VerifyAnnotationMyLimit {
private MyLimit limit;
private Class obj;
private ArrayList<Exception> ListExceptions;

public VerifyAnnotationMyLimit(Object object) throws Exception {
obj = object.getClass();
ListExceptions = new ArrayList<Exception>();
Field[] fields = obj.getDeclaredFields();
for (Field field : fields) {
// 设置field为private时设置可以访问权限,
field.setAccessible(true);
// 开始验证
verify(field, object);
// 重新对field设置权限
field.setAccessible(false);

}
}

public ArrayList<Exception> getListExceptions() {
return ListExceptions;
}

private void verify(Field field, Object object) throws Exception {
limit = field.getAnnotation(MyLimit.class);
// 检查这个field是否被MyLimit注释
if (!field.isAnnotationPresent(MyLimit.class)) {
return;
}
// 取出object对象中的field值
Object objectvalue = field.get(object);
String description = "".equals(limit.description()) ? field.getName()
: limit.description();

// 先验证是否为必填,如果必填且value为空,则抛出异常,如果不是必填,那我们
if (limit.isNotNull()) {
if ("".equals(objectvalue) || objectvalue == null) {
ListExceptions.add(new Exception(description + "不能为空"));
}
} else {
// 不是必填项先检查是否有值,没有就直接返回,有就继续向下验证
if (objectvalue == null) {
return;
}
}

if (limit.isInt()) {
int value = Integer.valueOf(objectvalue.toString());
if (value < limit.MinNum() || value > limit.MaxNum()) {
ListExceptions.add(new Exception(description + "必须在"
+ limit.MinNum() + "到" + limit.MaxNum() + "之间"));
}
return;
}

if (objectvalue.toString().length() < limit.MinLength()
|| objectvalue.toString().length() > limit.MaxLength()) {
ListExceptions.add(new Exception(description + "长度必须在"
+ limit.MinLength() + "到" + limit.MaxLength() + "之间"));
}
}
}Students类时注解的使用者:
public class Students {
private int id;
@MyLimit(description="学生的姓名",MaxLength=5,MinLength=2,isNotNull=true)
private String name;
@MyLimit(description="学生的年龄",isNotNull=true,isInt=true)
private int age;
@MyLimit(MaxLength=200,isNotNull=true)
private String addr;
@MyLimit(description="学生所在城市",MaxLength=20)
private String city;
set...get...
@Override
public String toString() {
return "Students [id=" + id + ", name=" + name + ", age=" + age
+ ", addr=" + addr + ", city=" + city + "]";
}
}在Students类中我们没有在id的属性上设置注解,所以不会对id进行验证;对name属性设置规定了长度在2到5之间,而且是必填项;在age上规定了这个是必填项,是一个int类型的,所以会使用注解对int类型默认的范围18到哦30之间;而对于addr属性只是规定了200长度,但是必填。
最后到了测试部分:

public static void main(String[] args) {
// TODO Auto-generated method stub
Students students = new Students();
students.setName("abcdefghijklmn");
students.setAddr("");
students.setAge(230);
try {//传人Students对象进行验证
VerifyAnnotationMyLimit annotationMyLimit = new VerifyAnnotationMyLimit(students);
if(annotationMyLimit.getListExceptions().size()!=0){
for (Exception exception : annotationMyLimit.getListExceptions()) {
System.out.println("错误:"+exception.getMessage());
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
e.printStackTrace();
}

System.out.println(students.toString());
}

if(annotationMyLimit.getListExceptions().size()!=0)判断是验证有错误;
for (Exception exception : annotationMyLimit.getListExceptions()) {
System.out.println("错误:"+exception.getMessage());//输出错误信息。
}

结果:



当我们改动一些值时:

students.setName("张三");
students.setAddr("xxx省xxx市xxx县");
students.setAge(23);


我们按照规定填写时就没有错误了,

但是这样还是有弊端的,因为我们是使用已经设置好属性的对象去验证了,等于是先给Students赋值,再去验证我们赋值是否正确,有了一些中间操作。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐