首页 > 编程知识 正文

java注解规则,java注解校验值

时间:2023-05-06 03:59:07 阅读:158457 作者:2717

说明Java定制注释的源代码原理(使用Java定制注释验证bean传入参数的有效性) ) )。

实现思路:

使用Java反射机制读取实体类属性的第一个注释,然后通过get方法获取并检查参数值,如果为空,则抛出异常。文件介绍:

1、CheckNull.java (自定义注释:验证非空字段) 2、UserRegister.java (用户实体类) 3、CommonUtils.java (公共工具类)

package com.seesun 2012.com mon.annotation; import Java.lang.annotation.documented; import Java.lang.annotation.element type; import Java.lang.annotation.inherited; import Java.lang.annotation.retention; import Java.lang.annotation.retention policy; import Java.lang.annotation.target; /** *自定义注释:非空字段* * @ author csdn:seesun 2012 * */@ documented @ inherited//接口、类、枚举和注释@ tarated 自己合适的逻辑(所谓的注释解析器) retention (retention policy.runtime ) public@interfacechecknull ) stringmessage ); } UserRegister.java (用户实体类) ) )。

package com.seesun 2012.com mon.entity; import java.io.Serializable; import com.seesun 2012.com mon.annotation.check null; /** *用户实体类* * @ authorseesun 2012 @ 163.com * */publicclassuserregisterimplementsserializable { privatestaticfion 自定义注释@checknull(message='用户名不能为空') private String userAccount; //自定义注释@checknull(message='密码不能为空')私有字符串密码; 公共字符串获取用户帐户() { return userAccount; } publicvoidsetuseraccount (string user account ) { this.userAccount=userAccount; }公共字符串获取密码() { return passWord; } publicvoidsetpassword (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.seesun 2012.com mon.utils; import java.beans.BeanInfo; import java.beans.Introspector; import Java.beans.property descriptor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.List; import com.seesun 2012.com mon.annotation.check null; import com.seesun 2012.com mon.exception.custbusinessexception; /** *公共工具类* * @author csdn:seesun20

12 * */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 fieldNamebean中对应的属性名称 * @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 csdn:seesun2012 * */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;}}


























注:以上内容仅提供参考和交流,请勿用于商业用途,如有侵权联系本人删除!

持续更新中…

如有对思路不清晰或有更好的解决思路,欢迎与本人交流,QQ群:273557553
你遇到的问题是小编创作灵感的来源!

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。