自定义注解验证参数
2017-12-06 22:14
295 查看
使用注解去验证某个对象属性是否按照我们的注解来赋值的。
例子:我们需要定义一个MyLimit的注解,这个注解里面规定了类属性的限制;编写注解解析;在类中属性使用注解;最后测试是否是我们需要的效果。
定义MyLimit注解:
[java] view plain copy print?@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:
[java] view plain copy print?import java.lang.reflect.Field;
ee43
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() + “之间”));
}
}
}
[java] view plain copy print?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 + “]”;
}
}
最后到了测试部分:
[java] view plain copy print?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());//输出错误信息。
}
结果:
当我们改动一些值时:
[java] view plain copy print?students.setName(“张三”);
students.setAddr(”xxx省xxx市xxx县”);
students.setAge(23);
我们按照规定填写时就没有错误了,
但是这样还是有弊端的,因为我们是使用已经设置好属性的对象去验证了,等于是先给Students赋值,再去验证我们赋值是否正确,有了一些中间操作。
例子:我们需要定义一个MyLimit的注解,这个注解里面规定了类属性的限制;编写注解解析;在类中属性使用注解;最后测试是否是我们需要的效果。
定义MyLimit注解:
[java] view plain copy print?@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;
}
@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:
[java] view plain copy print?import java.lang.reflect.Field;
ee43
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() + “之间”));
}
}
}
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类时注解的使用者:
[java] view plain copy print?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 + “]”;
}
}
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长度,但是必填。
最后到了测试部分:
[java] view plain copy print?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());
}
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());//输出错误信息。
}
结果:
当我们改动一些值时:
[java] view plain copy print?students.setName(“张三”);
students.setAddr(”xxx省xxx市xxx县”);
students.setAge(23);
students.setName("张三"); students.setAddr("xxx省xxx市xxx县"); students.setAge(23);
我们按照规定填写时就没有错误了,
但是这样还是有弊端的,因为我们是使用已经设置好属性的对象去验证了,等于是先给Students赋值,再去验证我们赋值是否正确,有了一些中间操作。
相关文章推荐
- SpringMVC验证框架Validation自定义注解实现传递参数到国际化资源文件
- SpringMVC验证框架Validation自定义注解实现传递参数到国际化资源文件
- SpringMVC验证框架Validation自定义注解实现传递参数到国际化资源文件
- cas 自定义参数及验证(10)
- 使用SpringBoot通过自定义注解+AOP+全局异常处理实现参数统一非空校验
- Jquery Validate 相关参数及常用的自定义验证规则
- springMVC自定义注解实现用户行为验证
- 【Spring】 (1)Aspect 自定义注解 使用该注解的地方 自动注入该注解里传的参数
- spring mvc自定义注解--访问时验证
- jQuery Validate 相关参数及常用的自定义验证规则
- spring 参数验证注解文档
- [置顶] spring boot 自定义注解实现权限验证
- springboot + 拦截器 + 注解 实现自定义权限验证
- 通过自定义注解或拦截器实现APP调用后接口全局权限验证
- java工具类,自定义注解参数校验 自定义注解redis缓存工具,文件工具 时间工具 加密等
- webservice-自定义注解处理参数加解密问题
- 基于Spring MVC框架JSR-303的自定义注解Validator验证实现
- XFire中的安全验证and自定义WSDL文档的参数名
- JAVA 自定义注解及参数获取
- 自定义注解验证