方法参数为Object与String类型的属性名
package com.mifu.core.util;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Field;
import java.util.Arrays;
/**
* 实体类属性控制
*
* @author zty
* @date 2022-08-11
*/
public class PropertyUtil {
/**
* 自动过滤基础类型,通过反射根据对象清空不必要属性
*
* @param t 实体对像
* @param retainFiled 保留字段(不会被清空)
* @return t 清空后的实体对象
*/
private static final String FILTERTYPES = "byte,short,int,long,float,double,boolean,char";
public static <T> T deleteProperties(T t, String... retainFiled) {
Class<?> aClass = t.getClass();
Field[] fields = aClass.getDeclaredFields();
Arrays.stream(fields).filter(f -> !ArrayUtils.contains(retainFiled, f.getName())).filter(field -> !FILTERTYPES.contains(field.getType().getName())).forEach(field -> {
Class<?> type = field.getType();
String name = type.getName();
try {
ReflectionUtils.makeAccessible(field);
field.set(t, null);
field.setAccessible(false);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
});
return t;
}
}
方法调用示例:
//sutdent属性有serialVersionUID、id、name、age、sex等
Student student = new Student;
//student对象中serialVersionUID、id、name不会被删除
BeanUtil.deleteProperties(student,"serialVersionUID","id","name");