校验数据对象不能为空


import org.apache.commons.lang3.ArrayUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 数据处理类
 **/
public class FundManagementHandler {

    /**
     * 校验数据对象不能为空
     * @param typeOne 类型一
     * @param typeTwo 类型二
     * @param objects 对象数组
     * @author 王超
     */
    public static boolean dataCheck(long typeOne,String typeTwo,Object... objects) {
        for (Object object : objects) {
            Field[] fields = object.getClass().getDeclaredFields();
            List<Field> collect = Arrays.stream(fields).filter(field -> field.isAnnotationPresent(DataNotNull.class)).collect(Collectors.toList());
            if (collect != null) {
                for(Field field:collect){
                    Annotation[] declaredAnnotations = field.getDeclaredAnnotations();
                    DataNotNull annotation = (DataNotNull) Arrays.stream(declaredAnnotations).filter(d -> d instanceof DataNotNull).collect(Collectors.toList()).get(0);
                    String investorIdAndType = typeTwo == null ? String.valueOf(typeOne) : typeOne+"-"+typeTwo;
                    if (ArrayUtils.contains(annotation.types(),investorIdAndType)) {
                        try {
                            field.setAccessible(true);
                            if (field.get(object) == null) {
                                System.out.println(annotation.message() + "字段不能为空,请核实。");
                                return false;
                            }
                        } catch (IllegalAccessException e) {
                            System.out.println("校验数据对象异常");
                            return false;
                        }
                    }
                }
            }
        }
        return true;
    }

    public static void main(String[] args) {
        TestData testData = new TestData();
        testData.setTest1("1");
        System.out.println(dataCheck(1,"1",testData));
    }
}

import java.lang.annotation.*;

/**
 * 数据不为Null
 **/
@Retention(RetentionPolicy.RUNTIME)
@Target(value = ElementType.FIELD)
public @interface DataNotNull {

    /**
     * 类型集合
     * 类型组成方式:1.类型一 2.类型一 + 拼接符号- + 类型二
     * 例:8符合类型一的都校验,8-1符合类型一(8)和类型二(1)拼接的都校验
     * @return String[]
     */
    String[] types();

    /**
     * 字段说明
     * @return String
     */
    String message();
}

/**
 * 测试对象
 **/
public class TestData {
    @DataNotNull(types = "1-1",message = "测试数据1")
    private String test1;

    public String getTest1() {
        return test1;
    }

    public void setTest1(String test1) {
        this.test1 = test1;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值