您的位置:首页 > 其它

跟王老师学注解(六):注解应用案例

2016-06-11 12:09 232 查看

跟王老师学注解(六):注解应用案例

主讲教师:王少华 QQ群号:483773664

一、需求

利用注解,做一个Bean的数据校验

要求:
用户名是否能为空,用户名的长度不能超过指定长度,不能少于指定长度

二、参考代码
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD, ElementType.PARAMETER })
public @interface MyValidate {
// 是否可以为空
boolean nullable() default false;

// 最大长度
int maxLength() default 0;

// 最小长度
int minLength() default 0;

// 参数或者字段描述,这样能够显示友好的异常信息
String description() default "";
}
public class User {
@MyValidate(description="用户名",minLength=6,maxLength=32,nullable=false)
private String userName;
public User(String userName) {
super();
this.userName = userName;
}
}
public class ValidateService {
// 解析的入口
public static void valid(Object object) throws Exception {
// 获取object的类型
Class<? extends Object> clazz = object.getClass();
// 获取该类型声明的成员
Field[] fields = clazz.getDeclaredFields();
// 遍历属性
for (Field field : fields) {
// 对于private私有化的成员变量,通过setAccessible来修改器访问权限
field.setAccessible(true);
validate(field, object);
// 重新设置会私有权限
field.setAccessible(false);
}
}

public static void validate(Field field,Object object) throws Exception{
String description;
Object value;

//获取对象的成员的注解信息
MyValidate dv=field.getAnnotation(MyValidate.class);
value=field.get(object);

if(dv==null)return;

description=dv.description().equals("")?field.getName():dv.description();

/*************注解解析工作开始******************/
if(!dv.nullable()){
if(value==null||value.toString()==""||"".equals(value.toString())){
throw new Exception(description+"不能为空");
}
}

if(value.toString().length()>dv.maxLength()&&dv.maxLength()!=0){
throw new Exception(description+"长度不能超过"+dv.maxLength());
}

if(value.toString().length()<dv.minLength()&&dv.minLength()!=0){
throw new Exception(description+"长度不能小于"+dv.minLength());
}

/*************注解解析工作结束******************/
}
}
public class Test {
public static void main(String[] args) {
User user = new User("张三");
try {
ValidateService.valid(user);
} catch (Exception e) {
e.printStackTrace();
}
user = new User("zhangsan");
try {
ValidateService.valid(user);
} catch (Exception e) {
e.printStackTrace();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  target blank telephone