java註解方式參數校正__javaWeb

來源:互聯網
上載者:User

1、註解類NotEmpty.java空值校正

package com.cmbc.umm.core.common.annotation;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Inherited;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Documented@Inherited@Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)public @interface NotEmpty {    //String value() default "";}

2、註解類CheckValue.javaRegex校正和空值校正

package com.cmbc.umm.core.common.annotation;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Inherited;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Documented@Inherited@Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)public @interface CheckValue {    String value() default "";}

3、解析工具類AnnotationUtil.java

package com.cmbc.umm.core.common.util;import java.lang.annotation.Annotation;import java.lang.reflect.Field;import java.util.regex.Matcher;import java.util.regex.Pattern;import org.apache.commons.lang3.ArrayUtils;import org.apache.commons.lang3.StringUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import com.cmbc.umm.core.common.annotation.CheckValue;import com.cmbc.umm.core.common.annotation.NotEmpty;public class AnnotationUtil {    private static final Logger logger = LoggerFactory.getLogger(AnnotationUtil.class);    /**     * 校正格式是否正確,如果@CheckValue() 沒有參數,則校正是否為空白     * 例子:@CheckValue("^[A-Za-z0-9_-]{1,32}$") 校正數字、字母、底線1到32位 : @CheckValue()     * 校正欄位是否為空白     *      * @param obj     * @return 如果返回null表示:校正通過     */    public static String checkValue(Object obj) {        return parseAnnotation(CheckValue.class, obj, true);    }    /**     * 校正是否為空白     *      * @param obj     * @return 如果返回null表示:校正通過     */    public static String checkEmpty(Object obj) {        return parseAnnotation(NotEmpty.class, obj, true);    }    private static String parseAnnotation(Class<? extends Annotation> aClazz, Object obj, boolean hasParent) {        StringBuilder sb = new StringBuilder();        boolean flag = false;        Class<?> clazz = obj.getClass();        Field[] fields = clazz.getDeclaredFields();        Field[] bothField = fields;        if (hasParent) {            Class<?> superClazz = clazz.getSuperclass();            Field[] superFields = superClazz.getDeclaredFields();            bothField = (Field[]) ArrayUtils.addAll(fields, superFields);        }        for (Field field : bothField) {            Annotation annotation = field.getAnnotation(aClazz);            if (annotation == null)                continue;            field.setAccessible(true);            try {                if (annotation instanceof CheckValue) {                    CheckValue cv = (CheckValue) annotation;                    String regex = cv.value();                    if (StringUtils.isEmpty(regex)) {                        // 輸入的Regex為空白,所以不做校正                        // continue;                        // NotEmpty ne = (NotEmpty)annotation;                        Object oValue = field.get(obj);                        if (oValue == null) {                            sb.append("欄位" + field.getName() + "不能為null|");                            flag = true;                        } else {                            if (oValue instanceof String) {                                String value = (String) oValue;                                if (StringUtils.isBlank(value)) {                                    sb.append("欄位" + field.getName() + "不可為空|");                                    flag = true;                                }                            } else {                                logger.info("欄位" + field.getName() + "不是字串,不能判斷是否為空白");                            }                        }                    } else {                        Pattern pattern = Pattern.compile(regex);                        String value = (String) field.get(obj);                        Matcher m = pattern.matcher(value);                        if (!m.matches()) {                            sb.append("欄位" + field.getName() + "格式錯誤|");                            flag = true;                        }                    }                } else if (annotation instanceof NotEmpty) {                    Object oValue = field.get(obj);                    if (oValue == null) {                        sb.append("欄位" + field.getName() + "不能為null|");                        flag = true;                    } else {                        if (oValue instanceof String) {                            String value = (String) oValue;                            if (StringUtils.isBlank(value)) {                                sb.append("欄位" + field.getName() + "不可為空|");                                flag = true;                            }                        } else {                            logger.info("欄位" + field.getName() + "不是字串,不能判斷是否為空白");                        }                    }                }            } catch (Exception e) {                sb.append(e.getMessage());                flag = true;                logger.error("解析註解出錯:", e);                // e.printStackTrace();            }        }        if (flag) {            return sb.toString();        } else {            return null;        }    }}

4、測試
1)People.java

package test;import com.cmbc.commons.annotation.CheckValue;import com.cmbc.commons.annotation.NotEmpty;public class People {    @CheckValue("^[A-Za-z0-9_-]{13,32}$")    private String id;    @NotEmpty    private String name;    @CheckValue    private int age;    public String getId() {        return id;    }    public void setId(String id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    @Override    public String toString() {        return "People [id=" + id + ", name=" + name + ", age=" + age + "]";    }}

2)Student.java

package test;import com.cmbc.commons.annotation.CheckValue;public class Student extends People{    @CheckValue    private String clazzNo;    public String getClazzNo() {        return clazzNo;    }    public void setClazzNo(String clazzNo) {        this.clazzNo = clazzNo;    }}

3)測試代碼

package test;import java.util.Map;import com.cmbc.commons.utils.AnnotationUtil;import com.cmbc.epay.umm.utils.EfficentDevUtil;public class Test {    private String name;    public static void main(String[] args) {        Student p = new Student();        p.setId("1111");        p.setName("");        p.setClazzNo(" ");        String s = AnnotationUtil.checkValue(p);        System.out.println(s);    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.