跟王老师学注解(六):注解应用案例
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(); } } }
相关文章推荐
- 详解链接的rel与target区别
- mysql 一个较特殊的问题:You can't specify target table 'wms_cabinet_form'
- event.currentTarget与event.target的区别介绍
- 详解JDK 5 Annotation 注解之@Target的用法介绍
- mysql中You can’t specify target table for update in FROM clause错误解决方法
- ora-00845 MEMORY_TARGET not supported on this system 的问题
- 产后抑郁情绪的调养
- 如何应对数据泄漏 不再重复索尼的失误(转自TT安全)
- Linux基础部分: 历史 现在 未来
- 回顾UNIX LINUX BSD架构
- 51CTO下载-千万级大型系统集成项目
- xargs的i参数
- 安装和使用memcached
- 抓包工具 tcpdump
- 轻松应对IDC机房带宽突然暴涨问题
- (转)TMG2010 日志队列
- (转)Overview of the Logging Improvements in Forefront Threat Management Gat
- Xcode中创建静态库,使用Target支持不同平台
- 抵抗勒索病毒的正确姿势——不要上来就封端口! 推荐
- 跟王老师学注解(五):利用反射读取注解信息