当前位置:   article > 正文

java利用注解及反射做通用的入参校验

java 注解和反射活用

一、原理:

  1、做一个field注解,注解有两个参数:是否必填、toString之后的最大长度

  2、对某个request类(或基类),使用注解标记某个字段的校验详情

  3、通用的static方法,利用反射获取属性的值,并做校验。不通过则抛出特定的异常

二、上代码:

异常类:

  1. package com.test;
  2. /**
  3. * 基础异常
  4. * @author zyydd
  5. * @date 2019/1/24 10:33
  6. * @version 1.0.0
  7. **/
  8. public class BaseException extends RuntimeException {
  9. /** 异常码 */
  10. private String code;
  11. /** 异常描述 */
  12. private String desc;
  13. public BaseException(){
  14. }
  15. public String getCode() {
  16. return code;
  17. }
  18. private void setCode(String code) {
  19. this.code = code;
  20. }
  21. public String getDesc() {
  22. return desc;
  23. }
  24. private void setDesc(String desc) {
  25. this.desc = desc;
  26. }
  27. public BaseException(String code, String desc) {
  28. this(code, desc, new Throwable(desc));
  29. }
  30. public BaseException(String code, String desc, Throwable canse) {
  31. super(new StringBuilder().append("code=").append(code).append(", desc=").append(desc).toString(), canse);
  32. this.setCode(code);
  33. this.setDesc(desc);
  34. }
  35. @Override
  36. public String toString() {
  37. return new StringBuilder().append(getClass().getName())
  38. .append("{code=").append(this.getCode())
  39. .append(", desc=").append(this.getDesc())
  40. .append("}").toString();
  41. }
  42. }

测试的request类:

  1. package com.test;
  2. /**
  3. * @author zyydd
  4. * @date 2019/6/13 18:29
  5. */
  6. public class TestChildRequest {
  7. /**
  8. * name
  9. */
  10. @ParameterAttr(isNecessary = true, lengthLimit = 10)
  11. private String name;
  12. /**
  13. * pin
  14. */
  15. @ParameterAttr(lengthLimit = 15)
  16. private String address;
  17. @ParameterAttr(isNecessary = true)
  18. private String school;
  19. private String other;
  20. public String getName() {
  21. return name;
  22. }
  23. public void setName(String name) {
  24. this.name = name;
  25. }
  26. public String getAddress() {
  27. return address;
  28. }
  29. public void setAddress(String address) {
  30. this.address = address;
  31. }
  32. public String getSchool() {
  33. return school;
  34. }
  35. public void setSchool(String school) {
  36. this.school = school;
  37. }
  38. public String getOther() {
  39. return other;
  40. }
  41. public void setOther(String other) {
  42. this.other = other;
  43. }
  44. }

field校验注解类:

  1. package com.test;
  2. import java.lang.annotation.ElementType;
  3. import java.lang.annotation.Retention;
  4. import java.lang.annotation.RetentionPolicy;
  5. import java.lang.annotation.Target;
  6. /**
  7. * @author zyydd
  8. * @date 2019/6/13 16:52
  9. */
  10. @Target(ElementType.FIELD)
  11. @Retention(RetentionPolicy.RUNTIME)
  12. public @interface ParameterAttr {
  13. /**
  14. * 是否必须,默认不必须
  15. *
  16. * @return
  17. */
  18. boolean isNecessary() default false;
  19. /**
  20. * 属性toSring之后,最大长度
  21. *
  22. * @return
  23. */
  24. int lengthLimit() default 0;
  25. }

通用校验工具类及main测试方法:

  1. package com.test;
  2. import org.apache.commons.lang.StringUtils;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import java.lang.reflect.Field;
  6. import java.util.ArrayList;
  7. import java.util.Arrays;
  8. import java.util.List;
  9. /**
  10. * @author zyydd
  11. * @date 2019/6/13 17:02
  12. */
  13. public class ParameterCheckUtils {
  14. private static Logger logger = LoggerFactory.getLogger(ParameterCheckUtils.class);
  15. public static void commonCheck(Object obj) throws IllegalAccessException {
  16. if (obj == null) {
  17. logger.error("obj can not be null!");
  18. throw new BaseException("9999", "obj can not be null!");
  19. }
  20. List<Field> fieldList = new ArrayList<Field>();
  21. Class clazz = obj.getClass();
  22. while (!Object.class.equals(clazz)) {
  23. fieldList.addAll(Arrays.asList(clazz.getDeclaredFields()));
  24. clazz = clazz.getSuperclass();
  25. }
  26. for (Field field : fieldList) {
  27. field.setAccessible(true);
  28. ParameterAttr attr = field.getAnnotation(ParameterAttr.class);
  29. if (attr == null) {
  30. continue;
  31. }
  32. Object paramObj = field.get(obj);
  33. if (attr.isNecessary()) {
  34. if (paramObj == null || StringUtils.isBlank(paramObj.toString())) {
  35. logger.error("class={} field={} can not be null!", obj.getClass().getName(), field.getName());
  36. throw new BaseException("9998", "field=" + field.getName() + " can not be null!");
  37. }
  38. }
  39. if (attr.lengthLimit() > 0 && paramObj != null && StringUtils.isNotBlank(paramObj.toString())) {
  40. if (paramObj.toString().length() > attr.lengthLimit()) {
  41. logger.error("class={} field={} length is too long! limit={} but length={}", obj.getClass().getName(), field.getName(), attr.lengthLimit(), paramObj.toString().length());
  42. throw new BaseException("9997", "field=" + field.getName() + " length is too long!");
  43. }
  44. }
  45. }
  46. logger.info("commonCheck success!");
  47. }
  48. public static void main(String[] args) throws IllegalAccessException {
  49. //正常数据
  50. TestChildRequest request1 = new TestChildRequest();
  51. request1.setName("王钢蛋");
  52. request1.setAddress("aabbccddeeaabbc");
  53. request1.setSchool("北京市智障二中");
  54. ParameterCheckUtils.commonCheck(request1);
  55. //为空数据
  56. try {
  57. ParameterCheckUtils.commonCheck(null);
  58. } catch (Exception e) {
  59. logger.error("error1 ", e);
  60. }
  61. //必填没传的数据
  62. try {
  63. TestChildRequest request2 = new TestChildRequest();
  64. request2.setName("王钢蛋");
  65. request2.setAddress("aabbccddeeaabbc");
  66. ParameterCheckUtils.commonCheck(request2);
  67. } catch (Exception e) {
  68. logger.error("error2 ", e);
  69. }
  70. //字段超长的数据
  71. try {
  72. TestChildRequest request3 = new TestChildRequest();
  73. request3.setName("王钢蛋");
  74. request3.setAddress("aabbccddeeaabbcc");
  75. request3.setSchool("北京市智障二中");
  76. ParameterCheckUtils.commonCheck(request3);
  77. } catch (Exception e) {
  78. logger.error("error3 ", e);
  79. }
  80. }
  81. }

执行结果:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/310831
推荐阅读
相关标签
  

闽ICP备14008679号