使用Java自定义注解校验bean传入参数合法性(Java自定义注解源码+原理解释)

阳光穿透心脏的1/2处 2022-05-25 10:13 300阅读 0赞

Java自定义注解源码+原理解释(使用Java自定义注解校验bean传入参数合法性)

实现思路:

  • 使用Java反射机制,读取实体类属性头部注解,通过get方法获取参数值进行校验,如果为空则进行异常抛出

文件介绍:

  • 1、CheckNull.java(自定义注解:校验非空字段)
  • 2、UserRegister.java(用户实体类)
  • 3、CommonUtils.java(公共工具类)
  • 4、Result.java(结果集返回包装类)
  • 5、CustBusinessException.java(自定义异常类)
  • 6、TestUtils.java(测试类)

CheckNull.java 类

  1. package com.seesun2012.common.annotation;
  2. import java.lang.annotation.Documented;
  3. import java.lang.annotation.ElementType;
  4. import java.lang.annotation.Inherited;
  5. import java.lang.annotation.Retention;
  6. import java.lang.annotation.RetentionPolicy;
  7. import java.lang.annotation.Target;
  8. /** * 自定义注解:校验非空字段 * * @author csdn:seesun2012 * */
  9. @Documented
  10. @Inherited
  11. // 接口、类、枚举、注解
  12. @Target(ElementType.FIELD)
  13. //只是在运行时通过反射机制来获取注解,然后自己写相应逻辑(所谓注解解析器)
  14. @Retention(RetentionPolicy.RUNTIME)
  15. public @interface CheckNull {
  16. String message();
  17. }

UserRegister.java(用户实体类)

  1. package com.seesun2012.common.entity;
  2. import java.io.Serializable;
  3. import com.seesun2012.common.annotation.CheckNull;
  4. /** * 用户实体类 * * @author seesun2012@163.com * */
  5. public class UserRegister implements Serializable{
  6. private static final long serialVersionUID = 1L;
  7. //自定义注解
  8. @CheckNull(message="用户名不能为空")
  9. private String userAccount;
  10. //自定义注解
  11. @CheckNull(message="密码不能为空")
  12. private String passWord;
  13. public String getUserAccount() { return userAccount; }
  14. public void setUserAccount(String userAccount) { this.userAccount = userAccount; }
  15. public String getPassWord() { return passWord; }
  16. public void setPassWord(String passWord) { this.passWord = passWord; }
  17. @Override
  18. public String toString() {
  19. StringBuilder sb = new StringBuilder();
  20. sb.append(getClass().getSimpleName());
  21. sb.append(" [");
  22. sb.append("Hash = ").append(hashCode());
  23. sb.append(", userAccount=").append(userAccount);
  24. sb.append(", passWord=").append(passWord);
  25. sb.append(", serialVersionUID=").append(serialVersionUID);
  26. sb.append("]");
  27. return sb.toString();
  28. }
  29. }

CommonUtils.java(公共工具类)

  1. package com.seesun2012.common.utils;
  2. import java.beans.BeanInfo;
  3. import java.beans.Introspector;
  4. import java.beans.PropertyDescriptor;
  5. import java.lang.reflect.Field;
  6. import java.lang.reflect.Method;
  7. import java.util.List;
  8. import com.seesun2012.common.annotation.CheckNull;
  9. import com.seesun2012.common.exception.CustBusinessException;
  10. /** * 公共工具类 * * @author csdn:seesun2012 * */
  11. public class CommonUtils{
  12. /** * 通过反射来获取javaBean上的注解信息,判断属性值信息,然后通过注解元数据来返回 */
  13. public static <T> boolean doValidator(T clas){
  14. Class<?> clazz = clas.getClass();
  15. Field[] fields = clazz.getDeclaredFields();
  16. for (Field field : fields) {
  17. CheckNull checkNull = field.getDeclaredAnnotation(CheckNull.class);
  18. if (null!=checkNull) {
  19. Object value = getValue(clas, field.getName());
  20. if (!notNull(value)) {
  21. throwExcpetion(checkNull.message());
  22. }
  23. }
  24. }
  25. return true;
  26. }
  27. /** * 获取当前fieldName对应的值 * * @param clas 对应的bean对象 * @param fieldName bean中对应的属性名称 * @return */
  28. public static <T> Object getValue(T clas,String fieldName){
  29. Object value = null;
  30. try {
  31. BeanInfo beanInfo = Introspector.getBeanInfo(clas.getClass());
  32. PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();
  33. for (PropertyDescriptor property : props) {
  34. if (fieldName.equals(property.getName())) {
  35. Method method = property.getReadMethod();
  36. value = method.invoke(clas, new Object[]{ });
  37. }
  38. }
  39. } catch (Exception e) {
  40. e.printStackTrace();
  41. }
  42. return value;
  43. }
  44. /** * 非空校验 * * @param value * @return */
  45. public static boolean notNull(Object value){
  46. if(null==value){
  47. return false;
  48. }
  49. if(value instanceof String && isEmpty((String)value)){
  50. return false;
  51. }
  52. if(value instanceof List && isEmpty((List<?>)value)){
  53. return false;
  54. }
  55. return null!=value;
  56. }
  57. public static boolean isEmpty(String str){
  58. return null==str || str.isEmpty();
  59. }
  60. public static boolean isEmpty(List<?> list){
  61. return null==list || list.isEmpty();
  62. }
  63. private static void throwExcpetion(String msg) {
  64. if(null!=msg){
  65. throw new CustBusinessException(msg);
  66. }
  67. }
  68. }

Result.java(结果集返回包装类)

  1. package com.seesun2012.common.entity;
  2. import java.io.Serializable;
  3. import java.util.HashMap;
  4. public class Result extends HashMap<String, Object> implements Serializable {
  5. private static final long serialVersionUID = 1L;
  6. public static final Result SUCCEED = new Result(0, "操作成功");
  7. public Result(int status, String massage) {
  8. super();
  9. this.put("status", status).put("message", massage);
  10. }
  11. public Result put(String key, Object value) {
  12. super.put(key, value);
  13. return this;
  14. }
  15. public static Result build(int i, String message) {
  16. return new Result(i, message);
  17. }
  18. }

CustBusinessException.java(自定义异常类)

  1. package com.seesun2012.common.exception;
  2. /** * 自定义异常类 * * @author csdn:seesun2012 * */
  3. public class CustBusinessException extends RuntimeException{
  4. private static final long serialVersionUID = 1L;
  5. public CustBusinessException(){
  6. }
  7. public CustBusinessException(String str){
  8. super(str);
  9. }
  10. public CustBusinessException(Throwable throwable){
  11. super(throwable);
  12. }
  13. public CustBusinessException(String str, Throwable throwable){
  14. super(str, throwable);
  15. }
  16. }

TestUtils.java(测试类)

  1. package com.seesun2012.test.utils;
  2. import com.seesun2012.common.entity.Result;
  3. import com.seesun2012.common.entity.UserRegister;
  4. import com.seesun2012.common.utils.CommonUtils;
  5. public class TestUtils{
  6. public static void main(String[] args) {
  7. UserRegister sss = new UserRegister();
  8. sss.setUserAccount("asdflkjasokdfj");
  9. System.out.println(insertUser(sss));
  10. }
  11. public static Result insertUser(UserRegister param){
  12. Result result = new Result(1, "新增失败");
  13. try {
  14. CommonUtils.doValidator(param);
  15. result = Result.build(0, "新增成功");
  16. } catch (Exception e) {
  17. result = Result.build(1, e.getMessage());
  18. }
  19. return result;
  20. }
  21. }

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


持续更新中…

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


发表评论

表情:
评论列表 (有 0 条评论,300人围观)

还没有评论,来说两句吧...

相关阅读

    相关 java定义校验注解

    随着业务的日趋复杂。我们对客户端传来的参数校验也越来越多。这么多的校验如果都写在业务逻辑中,业务代码看起来会很乱。 找时间学习了一下java的注解。特在此记录一下学习过程。