import com.pingan.characteristic.instance.Employee;
import org.junit.Test;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
/**
* @description: 反射特性测试类
* @author: DEZHI.HUANG
* @date: 2021-4-12 11:21
*/
public class HiReflex {
/**
* @Description 将所有无效参数改为null
* @Author DEZHI.HUANG
* @Date 2021-4-12 19:55
* @param obj 被处理的对象
* @return java.lang.Object
*/
public static Object changeInvalidToNull(Object obj) {
try {
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
String argsValue = field.get(obj) + "";
String str = argsValue.replaceAll(" ", "");
if (str.equals("") || str == null || str.equals("null")) {
field.set(obj, null);
}
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
/**
* @Description 校验对象所有字段不为 empty/null
* @Author DEZHI.HUANG
* @Date 2021-4-12 19:55
* @param obj 被校验的对象
* @return boolean
*/
public static boolean checkObjectField(Object obj) {
try {
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
String st = field.get(obj) + "";
String str = st.replaceAll(" ", "");
if (str.equals("") || str == null || str.equals("null")) {
return false;
}
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
/**
* @Description 校验对象指定字段是否有效
* @Author DEZHI.HUANG
* @Date 2021-4-12 19:56
* @param obj 被校验的对象
* @param args 被校验的字段集合
* @return boolean
*/
public static boolean checkObjectField(Object obj, String... args) {
try {
List<String> argsList = Arrays.asList(args);
//获取所有成员变量数组集合
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
// 若成员变量与传入的检验字段存在交集,则进行替换验证
if ((argsList.contains(field.getName()))) {
String argsValue = field.get(obj) + "";
String str = argsValue.replaceAll(" ", "");
if (str.equals("") || str == null || str.equals("null")) {
return false;
}
}
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
@Test
public void test1() {
Employee employee = new Employee();
boolean flag = checkObjectField(employee, "name","age","salary");
System.out.println(flag);
}
}