java自定义注解验证类的属性必填,最小、最大值、最小最大长度

编写不易,给个赞   

自定义注解,设置范围和注解方法
import java.lang.annotation.*;

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

    int max() default 2147483647;

    boolean isRequired() default false;

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

 

 

import java.math.BigDecimal;
import java.util.Date;


public class TestObj
{
    @DataLengh(min = 2,max = 5,message = "名称",isRequired = true)
    public String name;
    @DataLengh(min = 1,max = 120,message = "年龄")
    public Integer age;
    @DataLengh(min = 1,max = 120,message = "金额",isRequired = true)
    public Double money;
    @DataLengh(min = 1,max = 120,message = "双精度",isRequired = true)
    public BigDecimal decimal;
    @DataLengh(min = 1,max = 120,message = "float",isRequired = true)
    public float aFloat;
    @DataLengh(message = "日期",isRequired = true)
    public Date date;
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public TestObj(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public TestObj(String name, Integer age, double money, BigDecimal decimal, float aFloat, Date date) {
        this.name = name;
        this.age = age;
        this.money = money;
        this.decimal = decimal;
        this.aFloat = aFloat;
        this.date = date;
    }


    public TestObj() {
    }
}

 

 

import com.audaque.module.core.common.model.DataLengh;
import com.audaque.module.core.common.model.TestObj;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Date;

/**
 * 校验数据长度的帮助类
 *
 * @author LGH
 */
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();
            for (int i = 0; i < fields.length; i++) {// 遍历
                try {
                    // 得到属性
                    Field field = fields[i];
                    Annotation[] anns = field.getAnnotations();
                    DataLengh dataLen = null;
                    for (Annotation ann : anns) {
                        if (ann instanceof DataLengh)
                            dataLen = (DataLengh) 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();
            }
        }
    }

    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();
            }
        }

    }

    public static void main(String[] args) {
        try {

            TestObj testObj = new TestObj("22", 1, 1, new BigDecimal(12), 22, new Date());
            //   TestObj testObj1 = new TestObj(new Date());
            DataLenCheckHelper.checkAttributeValueLen(testObj);
        } catch (Exception e) {
            // TODO Auto-generated catch block
        }

    }

java自定义注解验证类的属性必填,最小、最大值、最小最大长度_第1张图片

 

你可能感兴趣的:(java技术)