Java自定义注解源码+原理解释(使用Java自定义注解校验bean传入参数合法性)
Java自定义注解源码+原理解释(使用Java自定义注解校验bean传入参数合法性)
前言:由于前段时间忙于写接口,在接口中需要做很多的参数校验,本着简洁、高效的原则,便写了这个小工具供自己使用(内容为缩减版,具体业务可自行扩展)
思路:使用Java反射机制,读取实体类属性头部注解,通过get方法获取参数值进行校验,如果为空则进行异常抛出。
CheckNull.java 类
package com.seesun2012.common.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 自定义注解:校验非空字段
*
* @author seesun2012@163.com
*
*/
@Documented
@Inherited
// 接口、类、枚举、注解
@Target(ElementType.FIELD)
//只是在运行时通过反射机制来获取注解,然后自己写相应逻辑(所谓注解解析器)
@Retention(RetentionPolicy.RUNTIME)
public @interface CheckNull {
String message();
}
Userregister.java 类
package com.seesun2012.common.entity;
import java.io.Serializable;
import com.seesun2012.common.annotation.CheckNull;
/**
* 用户注册实体类
*
* @author seesun2012@163.com
*
*/
public class Userregister implements Serializable{
private static final long serialVersionUID = 1L;
//自定义注解
@CheckNull(message="用户名不能为空")
private String userAccount;
//自定义注解
@CheckNull(message="密码不能为空")
private String passWord;
public String getUserAccount() { return userAccount; }
public void setUserAccount(String userAccount) { this.userAccount = userAccount; }
public String getPassWord() { return passWord; }
public void setPassWord(String passWord) { this.passWord = passWord; }
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", userAccount=").append(userAccount);
sb.append(", passWord=").append(passWord);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
CommonUtils.java 类
package com.seesun2012.common.utils;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import com.seesun2012.common.annotation.CheckNull;
import com.seesun2012.common.exception.CustBusinessException;
/**
* 公共工具类
*
* @author seesun2012@163.com
*
*/
public class CommonUtils{
/**
* 通过反射来获取javaBean上的注解信息,判断属性值信息,然后通过注解元数据来返回
*/
public static <T> boolean doValidator(T clas){
Class<?> clazz = clas.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
CheckNull checkNull = field.getDeclaredAnnotation(CheckNull.class);
if (null!=checkNull) {
Object value = getValue(clas, field.getName());
if (!notNull(value)) {
throwExcpetion(checkNull.message());
}
}
}
return true;
}
/**
* 获取当前fieldName对应的值
*
* @param clas 对应的bean对象
* @param fieldName bean中对应的属性名称
* @return
*/
public static <T> Object getValue(T clas,String fieldName){
Object value = null;
try {
BeanInfo beanInfo = Introspector.getBeanInfo(clas.getClass());
PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : props) {
if (fieldName.equals(property.getName())) {
Method method = property.getReadMethod();
value = method.invoke(clas, new Object[]{});
}
}
} catch (Exception e) {
e.printStackTrace();
}
return value;
}
/**
* 非空校验
*
* @param value
* @return
*/
public static boolean notNull(Object value){
if(null==value){
return false;
}
if(value instanceof String && isEmpty((String)value)){
return false;
}
if(value instanceof List && isEmpty((List<?>)value)){
return false;
}
return null!=value;
}
public static boolean isEmpty(String str){
return null==str || str.isEmpty();
}
public static boolean isEmpty(List<?> list){
return null==list || list.isEmpty();
}
private static void throwExcpetion(String msg) {
if(null!=msg){
throw new CustBusinessException(msg);
}
}
}
Result.java 类
package com.seesun2012.common.entity;
import java.io.Serializable;
import java.util.HashMap;
public class Result extends HashMap<String, Object> implements Serializable {
private static final long serialVersionUID = 1L;
public static final Result SUCCEED = new Result(0, "操作成功");
public Result(int status, String massage) {
super();
this.put("status", status).put("message", massage);
}
public Result put(String key, Object value) {
super.put(key, value);
return this;
}
public static Result build(int i, String message) {
return new Result(i, message);
}
}
CustBusinessException.java 类
package com.seesun2012.common.exception;
/**
* 自定义异常类
*
* @author seesun2012@163.com
*
*/
public class CustBusinessException extends RuntimeException{
private static final long serialVersionUID = 1L;
public CustBusinessException(){
}
public CustBusinessException(String str){
super(str);
}
public CustBusinessException(Throwable throwable){
super(throwable);
}
public CustBusinessException(String str, Throwable throwable){
super(str, throwable);
}
}
TestUtils.java 类
package com.seesun2012.test.utils;
import com.seesun2012.common.entity.Result;
import com.seesun2012.common.entity.Userregister;
import com.seesun2012.common.utils.CommonUtils;
public class TestUtils{
public static void main(String[] args) {
Userregister sss = new Userregister();
sss.setUserAccount("asdflkjasokdfj");
System.out.println(insertUser(sss));
}
public static Result insertUser(Userregister param){
Result result = new Result(1, "新增失败");
try {
CommonUtils.doValidator(param);
result = Result.build(0, "新增成功");
} catch (Exception e) {
result = Result.build(1, e.getMessage());
}
return result;
}
}
结语:该用户暂未添加
Java自定义注解源码+原理解释(使用Java自定义注解校验bean传入参数合法性)的更多相关文章
- 【java集合框架源码剖析系列】java源码剖析之TreeSet
本博客将从源码的角度带领大家学习TreeSet相关的知识. 一TreeSet类的定义: public class TreeSet<E> extends AbstractSet<E&g ...
- 【java集合框架源码剖析系列】java源码剖析之HashSet
注:博主java集合框架源码剖析系列的源码全部基于JDK1.8.0版本.本博客将从源码角度带领大家学习关于HashSet的知识. 一HashSet的定义: public class HashSet&l ...
- 【java集合框架源码剖析系列】java源码剖析之TreeMap
注:博主java集合框架源码剖析系列的源码全部基于JDK1.8.0版本.本博客将从源码角度带领大家学习关于TreeMap的知识. 一TreeMap的定义: public class TreeMap&l ...
- 【java集合框架源码剖析系列】java源码剖析之ArrayList
注:博主java集合框架源码剖析系列的源码全部基于JDK1.8.0版本. 本博客将从源码角度带领大家学习关于ArrayList的知识. 一ArrayList类的定义: public class Arr ...
- 【java集合框架源码剖析系列】java源码剖析之LinkedList
注:博主java集合框架源码剖析系列的源码全部基于JDK1.8.0版本. 在实际项目中LinkedList也是使用频率非常高的一种集合,本博客将从源码角度带领大家学习关于LinkedList的知识. ...
- 【java集合框架源码剖析系列】java源码剖析之HashMap
前言:之所以打算写java集合框架源码剖析系列博客是因为自己反思了一下阿里内推一面的失败(估计没过,因为写此博客已距阿里巴巴一面一个星期),当时面试完之后感觉自己回答的挺好的,而且据面试官最后说的这几 ...
- 【java集合框架源码剖析系列】java源码剖析之java集合中的折半插入排序算法
注:关于排序算法,博主写过[数据结构排序算法系列]数据结构八大排序算法,基本上把所有的排序算法都详细的讲解过,而之所以单独将java集合中的排序算法拿出来讲解,是因为在阿里巴巴内推面试的时候面试官问过 ...
- Java并发包源码学习系列:阻塞队列BlockingQueue及实现原理分析
目录 本篇要点 什么是阻塞队列 阻塞队列提供的方法 阻塞队列的七种实现 TransferQueue和BlockingQueue的区别 1.ArrayBlockingQueue 2.LinkedBloc ...
- Spring Boot @Enable*注解源码解析及自定义@Enable*
Spring Boot 一个重要的特点就是自动配置,约定大于配置,几乎所有组件使用其本身约定好的默认配置就可以使用,大大减轻配置的麻烦.其实现自动配置一个方式就是使用@Enable*注解,见其名知 ...
随机推荐
- django 实现电子支付功能
思路:调用第三方支付 API 接口实现支付功能.本来想用支付宝来实现第三方网站的支付功能的,但是在实际操作中发现支付宝没有 Python 接口,网上虽然有他人二次封装的的 Python 接口,但是对我 ...
- 【bzoj4811】[Ynoi2017]由乃的OJ 树链剖分/LCT+贪心
Description 给你一个有n个点的树,每个点的包括一个位运算opt和一个权值x,位运算有&,l,^三种,分别用1,2,3表示. 每次询问包含三个数x,y,z,初始选定一个数v.然后v依 ...
- PEP 8 – Style Guide for Python Code
原文:PEP 8 – Style Guide for Python Code PEP:8 题目:Python代码风格指南 作者:Guido van Rossum, www.yszx11.cnBarry ...
- ant实例
<?xml version="1.0" encoding="UTF-8" ?> <project name="javaTest&qu ...
- Navicat Premium 12.1.12.0破解版激活
声明:本文所提供的所有软件均来自于互联网,个人存放在此作为备用,以备将来不时之需,同时作为大家的分享和学习成果,仅供个人研究和学习使用,请勿用于商业用途,下载后请于24小时内删除,请支持正版! 附:二 ...
- Zookeeper客户端对比选择_4
Zookeeper客户端对比选择 本文思维导图 使用框架的好处是自带一套实用的API,但是Zookeeper虽然非常强大,但是社区却安静的可怕,版本更新较慢,下面会先从zookeeper原生API的不 ...
- caffe/proto/caffe.pb.h: No such file or director
caffe编译过程中遇到的为问题: fatal error: caffe/proto/caffe.pb.h: No such file or directory 解决方法: 用protoc从caffe ...
- mysql的时区错误问题,The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one
在使用springboot整合ssm和druid的时候出现数据库一个问题 org.springframework.web.util.NestedServletException: Request pr ...
- 【MySQL】20个经典面试题
转自:https://blog.csdn.net/suifenglie/article/details/78919045 Part1:经典题目 1.MySQL的复制原理以及流程 基本原理流程,3个线程 ...
- 【算法笔记】B1042 字符统计
1042 字符统计 (20 分) 请编写程序,找出一段给定文字中出现最频繁的那个英文字母. 输入格式: 输入在一行中给出一个长度不超过 1000 的字符串.字符串由 ASCII 码表中任意可见字符及空 ...