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