1. 程式人生 > >java註解方式引數校驗

java註解方式引數校驗

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.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 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)) {
                        // 輸入的正則表示式為空,所以不做校驗
                        // 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);
    }
}