本文转载自:https://www.jianshu.com/p/616924cd07e6

Java注解Annotation用起来很方便,也越来越流行,由于其简单、简练且易于使用等特点,很多开发工具都提供了注解功能,不好的地方就是代码入侵比较严重,所以使用的时候要有一定的选择性。

这篇文章将利用注解,来做一个Bean的数据校验。

下载

http://pan.baidu.com/s/1mgn2AHa

**项目结构 **

定义注解

该注解可以验证成员属性是否为空,长度,提供了几种常见的正则匹配,也可以使用自定义的正则去判断属性是否合法,同时可以为该成员提供描述信息。

定义注解

该注解可以验证成员属性是否为空,长度,提供了几种常见的正则匹配,也可以使用自定义的正则去判断属性是否合法,同时可以为该成员提供描述信息。

package org.xdemo.validation.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; import org.xdemo.validation.RegexType; /**
* 数据验证
* @author Goofy
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD,ElementType.PARAMETER})
public @interface DV { //是否可以为空
boolean nullable() default false; //最大长度
int maxLength() default 0; //最小长度
int minLength() default 0; //提供几种常用的正则验证
RegexType regexType() default RegexType.NONE; //自定义正则验证
String regexExpression() default ""; //参数或者字段描述,这样能够显示友好的异常信息
String description() default ""; }

注解的解析

package org.xdemo.validation.annotation.support;

import java.lang.reflect.Field;

import org.xdemo.validation.RegexType;
import org.xdemo.validation.annotation.DV;
import org.xdemo.validation.utils.RegexUtils;
import org.xdemo.validation.utils.StringUtils; /**
* 注解解析
* @author Goofy
*/
public class ValidateService { private static DV dv; public ValidateService() {
super();
} //解析的入口
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; //获取对象的成员的注解信息
dv=field.getAnnotation(DV.class);
value=field.get(object); if(dv==null)return; description=dv.description().equals("")?field.getName():dv.description(); /*************注解解析工作开始******************/
if(!dv.nullable()){
if(value==null||StringUtils.isBlank(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());
} if(dv.regexType()!=RegexType.NONE){
switch (dv.regexType()) {
case NONE:
break;
case SPECIALCHAR:
if(RegexUtils.hasSpecialChar(value.toString())){
throw new Exception(description+"不能含有特殊字符");
}
break;
case CHINESE:
if(RegexUtils.isChinese2(value.toString())){
throw new Exception(description+"不能含有中文字符");
}
break;
case EMAIL:
if(!RegexUtils.isEmail(value.toString())){
throw new Exception(description+"地址格式不正确");
}
break;
case IP:
if(!RegexUtils.isIp(value.toString())){
throw new Exception(description+"地址格式不正确");
}
break;
case NUMBER:
if(!RegexUtils.isNumber(value.toString())){
throw new Exception(description+"不是数字");
}
break;
case PHONENUMBER:
if(!RegexUtils.isPhoneNumber(value.toString())){
throw new Exception(description+"不是数字");
}
break;
default:
break;
}
} if(!dv.regexExpression().equals("")){
if(value.toString().matches(dv.regexExpression())){
throw new Exception(description+"格式不正确");
}
}
/*************注解解析工作结束******************/
}
}

用到的几个类

package org.xdemo.validation;

/**
* 常用的数据类型枚举
* @author Goofy
*
*/
public enum RegexType { NONE,
SPECIALCHAR,
CHINESE,
EMAIL,
IP,
NUMBER,
PHONENUMBER; }

其中正则验证类和字符串工具类请参考以下链接:

  1. SuperUtil之RegexUtils
  2. SuperUtil之StringUtils

使用方法

package org.xdemo.validation.test;

import org.xdemo.validation.RegexType;
import org.xdemo.validation.annotation.DV; public class User { @DV(description="用户名",minLength=6,maxLength=32,nullable=false)
private String userName; private String password; @DV(description="邮件地址",nullable=false,regexType=RegexType.EMAIL)
private String email; public User(){} public User(String userName, String password, String email) {
super();
this.userName = userName;
this.password = password;
this.email = email;
} public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}

测试代码

import org.xdemo.validation.annotation.support.ValidateService;

/**
* @author Goofy
*/
public class Test {
public static void main(String[] args){
User user=new User("张三", "xdemo.org", "252878950@qq.com");
try {
ValidateService.valid(user);
} catch (Exception e) {
e.printStackTrace();
}
user=new User("zhangsan","xdemo.org","xxx@");
try {
ValidateService.valid(user);
} catch (Exception e) {
e.printStackTrace();
}
user=new User("zhangsan","xdemo.org","");
try {
ValidateService.valid(user);
} catch (Exception e) {
e.printStackTrace();
}
}
}

运行效果

作者:会编程的小蚂蚁
链接:https://www.jianshu.com/p/616924cd07e6
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

Java自定义数据验证注解Annotation的更多相关文章

  1. SpringBoot08 请求方式、参数获取注解、参数验证、前后台属性名不一致问题、自定义参数验证注解、BeanUtils的使用

    1 请求方式 在定义一个Rest接口时通常会利用GET.POST.PUT.DELETE来实现数据的增删改查:这几种方式有的需要传递参数,后台开发人员必须对接收到的参数进行参数验证来确保程序的健壮性 1 ...

  2. JAVA提高五:注解Annotation

    今天我们学习JDK5.0中一个非常重要的特性,叫做注解.是现在非常流行的一种方式,可以说因为配置XML 比较麻烦或者比容易查找出错误,现在越来越多的框架开始支持注解方式,比如注明的Spring 框架, ...

  3. Java学习笔记:注解Annotation

    annotation的概念 In the Java computer programming language, an annotation is a form of syntactic metada ...

  4. Java反射reflection与注解annotation的应用(自动测试机)

    一.关于自动测试机 1.什么是自动测试机? 对类中的指定方法进行批量测试的工具 2.自动测试机有什么用? a.避免了冗长的测试代码 当类中的成员方法很多时,对应的测试代码可能会很长,使用测试能够让测试 ...

  5. [转]MVC自定义数据验证(两个时间的比较)

    本文转自:http://www.cnblogs.com/zhangliangzlee/archive/2012/07/26/2610071.html Model: public class Model ...

  6. java 编程基础:注解(Annotation Processing Tool)注解处理器 利用注解解读类属性生成XML文件

    APT的介绍: APT(Annotation Processing Tool)是一种注解处理工具,它对源代码文件进行检测,并找出源文件所包含的注解信息,然后针对注解信息进行额外的处理. 使用APT工具 ...

  7. excel自定义数据验证

    1. 判断必须为5位或者9位的数字 2. 自定义限制级别和提示消息

  8. 通过自定义Attribute及泛型extension封装数据验证过程

    需求来源: 在日常工作中,业务流程往往就是大量持续的数据流转.加工.展现过程,在这个过程中,不可避免的就是数据验证的工作.数据验证工作是个很枯燥的重复劳动,没有什么技术含量,需要的就是对业务流程的准确 ...

  9. asp.net mvc3 数据验证(二)——错误信息的自定义及其本地化

    原文:asp.net mvc3 数据验证(二)--错误信息的自定义及其本地化 一.自定义错误信息         在上一篇文章中所做的验证,在界面上提示的信息都是系统自带的,有些读起来比较生硬.比如: ...

随机推荐

  1. [LeetCode&Python] Problem 661. Image Smoother

    Given a 2D integer matrix M representing the gray scale of an image, you need to design a smoother t ...

  2. GitHub使用教程、注册与安装

    GitHub注册与安装 本文提供全流程,中文翻译.Chinar坚持将简单的生活方式,带给世人!(拥有更好的阅读体验 -- 高分辨率用户请调整网页缩放比例至200%) 1 进入GitHub官网:http ...

  3. Learning to Rank Short Text Pairs with Convolutional Deep Neural Networks(paper)

    本文重点: 和一般形式的文本处理方式一样,并没有特别大的差异,文章的重点在于提出了一个相似度矩阵 计算过程介绍: query和document中的首先通过word embedding处理后获得对应的表 ...

  4. lesson4Embedding-fastai

    dense layer:mnist识别中,需要十组dense权重矩阵来计算这十个输出内容,conv矩阵每一个元素乘以另一个矩阵的元素并相加,得到一个值,最后加上sigmoid(softmax在二元情况 ...

  5. 2017年秋软工-PSP总结报告

    一.回顾1 回顾本学期第一次作业[https://edu.cnblogs.com/campus/nenu/SWE2017FALL/homework/876]. ==>本学期我的第一次作业博客[h ...

  6. PTA——时间转换

    PTA 7-14 然后是几点 #include<stdio.h> int main() { int a,b,hour,min; scanf("%d%d",&a, ...

  7. C++学习(三十)(C语言部分)之 栈和队列

    数据结构1.保存数据 2.处理数据数组+操作增查删改 栈和队列是一种操作受限的线性表 栈 是先进后出 是在一端进行插入删除的操作--->栈顶 另一端叫做栈底(栈和栈区是两个概念)(是一种数据结构 ...

  8. 实验吧—Web——WP之 上传绕过

    我们先上传一个png文件,发现他说必须上传后缀名为PHP的文件才可以,那么,我们尝试一下,PHP文件 但是他又说不被允许的文件类型 在上传绕过里最有名的的就是00截断,那么我们就先要抓包 在这里我们需 ...

  9. uboot2014.10移植(一)

    最新有点时间,所以想折腾点东西,于是拿起了几年前的TQ2440玩玩,下载了uboot2014.10版本,准备移植到板子上去,没想到折腾环境都折腾了一下午. 1.工具链安装 我的工具链直接用命令安装的: ...

  10. codeforce 804B Minimum number of steps

    cf劲啊 原题: We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each ...