自定义注解对象属性长度必填项校验

281 阅读3分钟

编写不易,给个赞 话不多说直接上代码

package com.product.news.inter;

import java.lang.annotation.*;

/**
 * @author chenhao
 * @create 2021/12/27 10:32
 */

@Target({ ElementType.FIELD, ElementType.TYPE })
@Inherited
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface DataLength {
    int min() default 0;

    int max() default 2147483647;

    boolean isRequired() default false;

    String message() default "字段长度不符合";
}

验证代码支持String,Integer,BigDecimal,Float,Double类型数据

package com.product.news.help;

import com.product.news.inter.DataLength;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author chenhao
 * @create 2021/12/27 11:06
 */
public class DataLenCheckHelper {

    /**
     * 校验数据属性至
     *
     * @param obj
     * @throws Exception
     */
    @SuppressWarnings("rawtypes")
    public static void checkAttributeValueLen(Object obj) throws Exception {
        if (null != obj) {
            // 得到class
            Class cls = obj.getClass();
            System.out.println("校验对象中参数的数据长度是否符合要求,校验对象:" + cls.getName());
            // 得到所有属性
//            Field[] fields = cls.getDeclaredFields();
            List<Field> fieldList = new ArrayList<>();
            Class<?> cl = cls;
            while (cl != null){
                fieldList.addAll(new ArrayList<>(Arrays.asList(cl.getDeclaredFields())));
                cl = cl.getSuperclass();
            }
            Field[] fields = new Field[fieldList.size()];
            fieldList.toArray(fields);
            for (int i = 0; i < fieldList.size(); i++) {// 遍历
                try {
                    // 得到属性
                    Field field = fields[i];
                    Annotation[] anns = field.getAnnotations();
                    DataLength dataLen = null;
                    for (Annotation ann : anns) {
                        if (ann instanceof DataLength){
                            dataLen = (DataLength) ann;
                        }
                    }
                    // 判断该属性是否有校验数据长度的注解
                    if (null != dataLen) {
                        // 打开私有访问
                        field.setAccessible(true);
                        // 获取属性
                        String name = field.getName();
                        // 获取属性值
                        Object value = field.get(obj);
                        // 获取最小长度
                        int minLen = dataLen.min();
                        // 获取最大长度
                        int maxLen = dataLen.max();
                        // 获取字段必填
                        boolean isRequired = dataLen.isRequired();
                        // 获取字段备注
                        String message = dataLen.message();
                        // 数据的长度
                        String data = null;
                        // 一个个赋值
                        /**
                         * 验证必填
                         */
                        if (isRequired) {
                            if (value == null) {
                                System.out.print("对象:" + cls.getName() + "中存在不符合条件的参数,参数名:" + name + "(" + message + "),要求必填");
                            }
                            if (value == null || value instanceof String) {
                                data = (String) value;
                                if (data.length() == 0) {
                                    System.out.print("对象:" + cls.getName() + "中存在不符合条件的参数,参数名:" + name + "(" + message + "), 要求必填");
                                }
                            }
                        }

                        if (null != value && value instanceof String) {
                            checkStringLegth(name, value, data, cls, minLen, maxLen, message);
                        } else if (null != value && value instanceof Integer) {
                            checkInter(name, value, data, cls, minLen, maxLen, message);
                        } else if (null != value && value instanceof BigDecimal) {
                            checkBigDecimal(name, value, data, cls, minLen, maxLen, message);
                        } else if (null != value && value instanceof Float) {
                            checkFloat(name, value, data, cls, minLen, maxLen, message);
                        } else if (null != value && value instanceof Float) {
                            checkDouble(name, value, data, cls, minLen, maxLen, message);
                        }
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void checkStringLegth(String name, Object value, String data, Class cls, int minLen, int maxLen, String message) throws Exception {
        int vaLen = 0;
        data = (String) value;
        vaLen = data.length();
        if (minLen != 0) {
            if (minLen > vaLen || vaLen > maxLen) {
                System.out.print("对象:" + cls.getName() + "中存在不符合条件的参数,参数名:" + name + "(" + message + "),参数值:" + data + ",指定的数据长度范围:(" + minLen + "," + maxLen + ")实际长度:" + vaLen
                        + ",不符合条件");
                throw new Exception();
            }
        } else {
            if (vaLen > maxLen) {
//                System.out.print("对象:" + cls.getName() + "中存在不符合条件的参数,参数名:" + name + "(" + message + "),参数值:" + data + ",指定的数据最大长度:" + maxLen + ",实际长度:" + vaLen
//                        + ",不符合条件");
                throw new Exception("对象:" + cls.getName() + "中存在不符合条件的参数,参数名:" + name + "(" + message + "),参数值:" + data + ",指定的数据最大长度:" + maxLen + ",实际长度:" + vaLen
                        + ",不符合条件");
            }
        }
    }

    public static void checkInter(String name, Object value, String data, Class cls, int minLen, int maxLen, String message) throws Exception {
        int vaLen = 0;
        vaLen = (Integer) value;
// vaLen = data.length();
        if (minLen != 0) {
            if (minLen > vaLen || vaLen > maxLen) {
                System.out.print("对象:" + cls.getName() + "中存在不符合条件的参数,参数名:" + name + "(" + message + "),参数值:" + vaLen + ",指定的数据范围:(" + minLen + "," + maxLen + ")实际值:" + vaLen
                        + ",不符合条件");
                throw new Exception();
            }
        } else {
            if (vaLen > maxLen) {
                System.out.print("对象:" + cls.getName() + "中存在不符合条件的参数,参数名:" + name + "(" + message + "),参数值:" + vaLen + ",指定的数据最大值:" + maxLen + ",实际值:" + vaLen
                        + ",不符合条件");
                throw new Exception();
            }
        }
    }

    public static void checkBigDecimal(String name, Object value, String data, Class cls, int minLen, int maxLen, String message) throws Exception {
        BigDecimal bigDecimal;
        bigDecimal = (BigDecimal) value;
        if (minLen != 0) {
            System.out.println(bigDecimal.compareTo(new BigDecimal(minLen)));
            System.out.println(bigDecimal.compareTo(new BigDecimal(maxLen)));
            if (bigDecimal.compareTo(new BigDecimal(minLen)) < 0 || bigDecimal.compareTo(new BigDecimal(maxLen)) > 0) {
                System.out.print("对象:" + cls.getName() + "中存在不符合条件的参数,参数名:" + name + "(" + message + "),参数值:" + bigDecimal + ",指定的数据范围:(" + minLen + "," + maxLen + ")实际值:" + bigDecimal
                        + ",不符合条件");
                throw new Exception();
            }
        } else {
            if (bigDecimal.compareTo(new BigDecimal(maxLen)) > 0) {
                System.out.print("对象:" + cls.getName() + "中存在不符合条件的参数,参数名:" + name + "(" + message + "),参数值:" + bigDecimal + ",指定的数据最大值:" + maxLen + ",实际值:" + bigDecimal
                        + ",不符合条件");
                throw new Exception();
            }
        }
    }

    public static void checkFloat(String name, Object value, String data, Class cls, int minLen, int maxLen, String message) throws Exception {
        Float afloat;
        afloat = (Float) value;
        if (minLen != 0) {
            if (minLen > afloat || afloat >= maxLen) {
                System.out.print("对象:" + cls.getName() + "中存在不符合条件的参数,参数名:" + name + "(" + message + "),参数值:" + afloat + ",指定的数据范围:(" + minLen + "," + maxLen + ")实际值:" + afloat
                        + ",不符合条件");
                throw new Exception();
            }
        } else {
            if (maxLen > afloat) {
                System.out.print("对象:" + cls.getName() + "中存在不符合条件的参数,参数名:" + name + "(" + message + "),参数值:" + afloat + ",指定的数据最大值:" + maxLen + ",实际值:" + afloat
                        + ",不符合条件");
                throw new Exception();
            }
        }
    }
    public static void checkDouble(String name, Object value, String data, Class cls, int minLen, int maxLen, String message) throws Exception {
        Double adouble;
        adouble = (Double) value;
        if (minLen != 0) {
            if (minLen > adouble || adouble >= maxLen) {
                System.out.print("对象:" + cls.getName() + "中存在不符合条件的参数,参数名:" + name + "(" + message + "),参数值:" + adouble + ",指定的数据范围:(" + minLen + "," + maxLen + ")实际值:" + adouble
                        + ",不符合条件");
                throw new Exception();
            }
        } else {
            if (maxLen > adouble) {
                System.out.print("对象:" + cls.getName() + "中存在不符合条件的参数,参数名:" + name + "(" + message + "),参数值:" + adouble + ",指定的数据最大值:" + maxLen + ",实际值:" + adouble
                        + ",不符合条件");
                throw new Exception();
            }
        }
    }


}
package com.product.news.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.product.core.mp.base.BaseEntity;
import com.product.core.tool.utils.DateUtil;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;

import java.io.Serializable;
import java.time.LocalDateTime;

/**
 * 关注实体类
 *
 * @author product
 * @since 2019-10-10
 */
@Data
public class Follow extends BaseEntity{

    private static final long serialVersionUID = 1L;

    /**
     * 主键
     */
    @ApiModelProperty(value = "主键")
    @TableId(value = "id", type = IdType.ID_WORKER)
    private Long id;
    /**
     * 关注人主键
     */
    @ApiModelProperty(value = "关注人主键")
    @DataLength(min = 1,max = 255,message = "关注人",isRequired = true)
    private Integer followUser;
    /**
     * 稿件主键
     */
    @ApiModelProperty(value = "关注对象主键")
    private Long objectId;
    /**
     * 关注时间
     */
    @DateTimeFormat(pattern = DateUtil.PATTERN_DATETIME)
    @ApiModelProperty(value = "关注时间")
    private LocalDateTime followTime;
    
    /**
     * 关注类型
     */
    @ApiModelProperty(value = "关注对象类型)
    private Integer followType;

    @DataLength(min = 1,max = 255,message = "关注标题",isRequired = true)
    private String followTitle;

}

测试验证长度

import com.product.news.entity.Follow;
import com.product.news.help.DataLenCheckHelper;
/**
 * @author chenhao
 * @create 2021/12/27 15:17
 */
public class Test {
    public static void main(String[] args) {
        Follow follow = new Follow();
        follow.setObjectId(1L);
        follow.setFollowTitle("中国万岁中国万岁中国万岁中国万岁中国万岁中国万岁");
        try {
            DataLenCheckHelper.checkAttributeValueLen(follow);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}