自定义注解验证

来源:互联网 发布:设计院面试问题知乎 编辑:程序博客网 时间:2024/06/04 18:24

注解类

import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target({ ElementType.FIELD, ElementType.METHOD })@Retention(RetentionPolicy.RUNTIME)public @interface Attribute {    // 字段属性说明    String name() default "";    // 字段是否强制校验必填,优于required,在任何校验方法内都会校验该字段是否为空    boolean everyRequired() default false;    // 字段是否必填    boolean required() default false;    // 字段固定长度限制    int length() default 0;    // 字段最大长度限制    int maxLength() default 0;    // 日期类型格式限制    String dateFormat() default "";    // 赋值限制列表,用于下拉列表    String[] valueSetLimit() default {};}

验证类

import java.lang.reflect.Field;import java.lang.reflect.InvocationHandler;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Modifier;import java.lang.reflect.Proxy;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.HashMap;import java.util.Map;import org.apache.commons.lang3.StringUtils;import com.hikvision.annotation.Attribute;import java.util.Arrays;public class ParamVaildate {    /***     * 设置类属性的注解值,设置后该注解值将持续生效,若只是暂时需要改变,请在结束后再次调用更改回去     *      * @param object     *            对象类     * @param atts     *            属性数组     * @param anns     *            注解数组     * @param values     *            更改后的注解值数组     */    public static void setAttributeAnnotation(Object object, String[] atts, String[] anns, Object[] vals) {        for (int i = 0; i < atts.length; i++) {            setAttributeAnnotation(object, atts[i], anns[i], vals[i]);        }    }    public static void setAttributeAnnotation(Object object, String att, String ann, Object val) {        try {            Field field = object.getClass().getDeclaredField(att);            InvocationHandler h = Proxy.getInvocationHandler(field.getAnnotation(Attribute.class));            Field hField = h.getClass().getDeclaredField("memberValues");            hField.setAccessible(true);            Map memberValues = (Map) hField.get(h);            memberValues.put(ann, val);        } catch (NoSuchFieldException | SecurityException e) {            e.printStackTrace();        } catch (IllegalArgumentException e) {            e.printStackTrace();        } catch (IllegalAccessException e) {            e.printStackTrace();        }    }    /***     * 验证类所有属性     *      * @param object     * @return     */    public static Map<String, Object> vaildateAll(Object object) {        Map<String, Object> vailMap = new HashMap<String, Object>();        if (object == null) {            vailMap.put("errorCode", "1");            vailMap.put("errorMessage", "验证的对象为空,请检查");            return vailMap;        }        vailMap.put("errorCode", "0");        Field[] fields = object.getClass().getDeclaredFields();        try {            for (Field field : fields) {                // 排除static属性                if (Modifier.isStatic(field.getModifiers())) {                    continue;                }                Attribute att = field.getAnnotation(Attribute.class);                // 排除没有注解的属性                if (att == null) {                    continue;                }                String value = (String) object.getClass()                        .getMethod("get" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1))                        .invoke(object);                // 强制校验必填                if (att.everyRequired() && StringUtils.isEmpty(value)) {                    vailMap.put("errorCode", "1");                    vailMap.put("errorMessage",                            field.getAnnotation(Attribute.class).name() + "(" + field.getName() + ")不允许为空,请检查参数");                    break;                }                // 必填校验                if (att.required() && StringUtils.isEmpty(value)) {                    vailMap.put("errorCode", "1");                    vailMap.put("errorMessage",                            field.getAnnotation(Attribute.class).name() + "(" + field.getName() + ")不允许为空,请检查参数");                    break;                }                // 固定长度校验                if (value != null && att.length() > 0 && value.length() != att.length()) {                    vailMap.put("errorCode", "1");                    vailMap.put("errorMessage", field.getAnnotation(Attribute.class).name() + "(" + field.getName()                            + ")固定长度限制为" + att.length() + ",实际长度为" + value.length() + ",请检查参数");                    break;                }                // 最大长度校验                if (value != null && att.maxLength() > 0 && value.length() > att.maxLength()) {                    vailMap.put("errorCode", "1");                    vailMap.put("errorMessage", field.getAnnotation(Attribute.class).name() + "(" + field.getName()                            + ")最大长度限制为" + att.maxLength() + ",实际长度为" + value.length() + ",请检查参数");                    break;                }                // 日期类型校验                if (value != null && att.dateFormat().length() > 0) {                    SimpleDateFormat sdf = new SimpleDateFormat(att.dateFormat());                    try {                        sdf.parse(value);                    } catch (ParseException e) {                        e.printStackTrace();                        vailMap.put("errorCode", "1");                        vailMap.put("errorMessage", field.getAnnotation(Attribute.class).name() + "(" + field.getName()                                + ")日期类型限制为" + att.dateFormat() + "格式,请检查参数");                        break;                    }                }                // 赋值限制列表校验                if (value != null && att.valueSetLimit().length > 0) {                    boolean limitFlag = false;                    for (int index = 0; index < att.valueSetLimit().length; index++) {                        if (value.equals(att.valueSetLimit()[index])) {                            limitFlag = true;                            continue;                        }                    }                    if (!limitFlag) {                        vailMap.put("errorCode", "1");                        vailMap.put("errorMessage", field.getAnnotation(Attribute.class).name() + "(" + field.getName()                                + ")赋值限制列表为" + Arrays.toString(att.valueSetLimit()) + ",当前设值为'" + value + "'不符合规范,请检查参数");                        break;                    }                }            }        } catch (NoSuchMethodException e) {            e.printStackTrace();            vailMap.put("errorCode", "1");            vailMap.put("errorMessage", "未在对应的实体中找到该方法:" + e.getMessage());        } catch (IllegalArgumentException e) {            e.printStackTrace();            vailMap.put("errorCode", "1");            vailMap.put("errorMessage", e.getMessage());        } catch (IllegalAccessException e) {            e.printStackTrace();            vailMap.put("errorCode", "1");            vailMap.put("errorMessage", e.getMessage());        } catch (InvocationTargetException e) {            e.printStackTrace();            vailMap.put("errorCode", "1");            vailMap.put("errorMessage", e.getMessage());        } catch (SecurityException e) {            e.printStackTrace();            vailMap.put("errorCode", "1");            vailMap.put("errorMessage", e.getMessage());        }        return vailMap;    }    /***     * 验证类所有非空属性     *      * @param object     * @return     */    public static Map<String, Object> vaildateIsNotNulllAtt(Object object) {        Map<String, Object> vailMap = new HashMap<String, Object>();        if (object == null) {            vailMap.put("errorCode", "1");            vailMap.put("errorMessage", "验证的对象为空,请检查");            return vailMap;        }        vailMap.put("errorCode", "0");        Field[] fields = object.getClass().getDeclaredFields();        try {            for (Field field : fields) {                // 排除static属性                if (Modifier.isStatic(field.getModifiers())) {                    continue;                }                Attribute att = field.getAnnotation(Attribute.class);                // 排除没有注解的属性                if (att == null) {                    continue;                }                String value = (String) object.getClass()                        .getMethod("get" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1))                        .invoke(object);                // 强制校验必填                if (att.everyRequired() && StringUtils.isEmpty(value)) {                    vailMap.put("errorCode", "1");                    vailMap.put("errorMessage",                            field.getAnnotation(Attribute.class).name() + "(" + field.getName() + ")不允许为空,请检查参数");                    break;                }                // 非空且必填,不为空字符校验                if (value != null && att.required() && "".equals(value.trim())) {                    vailMap.put("errorCode", "1");                    vailMap.put("errorMessage",                            field.getAnnotation(Attribute.class).name() + "(" + field.getName() + ")不允许为空,请检查参数");                    break;                }                // 固定长度校验                if (value != null && att.length() > 0 && value.length() != att.length()) {                    vailMap.put("errorCode", "1");                    vailMap.put("errorMessage", field.getAnnotation(Attribute.class).name() + "(" + field.getName()                            + ")固定长度限制为" + att.length() + ",实际长度为" + value.length() + ",请检查参数");                    break;                }                // 最大长度校验                if (value != null && att.maxLength() > 0 && value.length() > att.maxLength()) {                    vailMap.put("errorCode", "1");                    vailMap.put("errorMessage", field.getAnnotation(Attribute.class).name() + "(" + field.getName()                            + ")最大长度限制为" + att.maxLength() + ",实际长度为" + value.length() + ",请检查参数");                    break;                }                // 日期类型校验                if (value != null && att.dateFormat().length() > 0) {                    SimpleDateFormat sdf = new SimpleDateFormat(att.dateFormat());                    try {                        sdf.parse(value);                    } catch (ParseException e) {                        e.printStackTrace();                        vailMap.put("errorCode", "1");                        vailMap.put("errorMessage", field.getAnnotation(Attribute.class).name() + "(" + field.getName()                                + ")日期类型限制为" + att.dateFormat() + "格式,请检查参数");                        break;                    }                }            }        } catch (NoSuchMethodException e) {            e.printStackTrace();            vailMap.put("errorCode", "1");            vailMap.put("errorMessage", "未在对应的实体中找到该方法:" + e.getMessage());        } catch (IllegalArgumentException e) {            e.printStackTrace();            vailMap.put("errorCode", "1");            vailMap.put("errorMessage", e.getMessage());        } catch (IllegalAccessException e) {            e.printStackTrace();            vailMap.put("errorCode", "1");            vailMap.put("errorMessage", e.getMessage());        } catch (InvocationTargetException e) {            e.printStackTrace();            vailMap.put("errorCode", "1");            vailMap.put("errorMessage", e.getMessage());        } catch (SecurityException e) {            e.printStackTrace();            vailMap.put("errorCode", "1");            vailMap.put("errorMessage", e.getMessage());        }        return vailMap;    }    /***     * 根据传入的类名称和属性数组验证     *      * @param object     * @param atts     * @return     */    public static Map<String, Object> vaildateAtts(Object object, String[] atts) {        Map<String, Object> vailMap = new HashMap<String, Object>();        if (object == null) {            vailMap.put("errorCode", "1");            vailMap.put("errorMessage", "验证的对象为空,请检查");            return vailMap;        }        vailMap.put("errorCode", "0");        try {            for (int i = 0; i < atts.length; i++) {                Field field = object.getClass().getDeclaredField(atts[i]);                Attribute att = field.getAnnotation(Attribute.class);                // 排除没有注解的属性                if (att == null) {                    continue;                }                String value = (String) object.getClass()                        .getMethod("get" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1))                        .invoke(object);                // 强制校验必填                if (att.everyRequired() && StringUtils.isEmpty(value)) {                    vailMap.put("errorCode", "1");                    vailMap.put("errorMessage",                            field.getAnnotation(Attribute.class).name() + "(" + field.getName() + ")不允许为空,请检查参数");                    break;                }                // 必填校验                if (att.required() && StringUtils.isEmpty(value)) {                    vailMap.put("errorCode", "1");                    vailMap.put("errorMessage",                            field.getAnnotation(Attribute.class).name() + "(" + field.getName() + ")不允许为空,请检查参数");                    break;                }                // 固定长度校验                if (value != null && att.length() > 0 && value.length() != att.length()) {                    vailMap.put("errorCode", "1");                    vailMap.put("errorMessage", field.getAnnotation(Attribute.class).name() + "(" + field.getName()                            + ")固定长度限制为" + att.length() + ",实际长度为" + value.length() + ",请检查参数");                    break;                }                // 最大长度校验                if (value != null && att.maxLength() > 0 && value.length() > att.maxLength()) {                    vailMap.put("errorCode", "1");                    vailMap.put("errorMessage", field.getAnnotation(Attribute.class).name() + "(" + field.getName()                            + ")最大长度限制为" + att.maxLength() + ",实际长度为" + value.length() + ",请检查参数");                    break;                }                // 日期类型校验                if (value != null && att.dateFormat().length() > 0) {                    SimpleDateFormat sdf = new SimpleDateFormat(att.dateFormat());                    try {                        sdf.parse(value);                    } catch (ParseException e) {                        e.printStackTrace();                        vailMap.put("errorCode", "1");                        vailMap.put("errorMessage", field.getAnnotation(Attribute.class).name() + "(" + field.getName()                                + ")日期类型限制为" + att.dateFormat() + "格式,请检查参数");                        break;                    }                }            }        } catch (NoSuchFieldException e) {            e.printStackTrace();            vailMap.put("errorCode", "1");            vailMap.put("errorMessage", "未在对应的实体中找到该属性:" + e.getMessage());        } catch (NoSuchMethodException e) {            e.printStackTrace();            vailMap.put("errorCode", "1");            vailMap.put("errorMessage", "未在对应的实体中找到该方法:" + e.getMessage());        } catch (IllegalArgumentException e) {            e.printStackTrace();            vailMap.put("errorCode", "1");            vailMap.put("errorMessage", e.getMessage());        } catch (IllegalAccessException e) {            e.printStackTrace();            vailMap.put("errorCode", "1");            vailMap.put("errorMessage", e.getMessage());        } catch (SecurityException e) {            e.printStackTrace();            vailMap.put("errorCode", "1");            vailMap.put("errorMessage", e.getMessage());        } catch (InvocationTargetException e) {            e.printStackTrace();            vailMap.put("errorCode", "1");            vailMap.put("errorMessage", e.getMessage());        }        return vailMap;    }}

model类

public class PartnerModel{    @Attribute(name = "名称", everyRequired = true, dateFormat = "YYYY-MM-DD")    private String name;    setget..;}
原创粉丝点击