序言:在开发Excel数据导入的时候,将导入的数据映射到List泛型集合中时,发现对象的字符串属性有很多空格,数据不规范,保存到数据库不好,需要对这些数据进行去空格操作,下面是具体的操作。
ObjectUtil工具类
import java.util.*;
import java.lang.reflect.Field;
public class ObjectUtil {
public static void objectToTrim(Object object) {
Map<String,String> map = new HashMap<>();
Field[] fields = getAllFields(object);
for (Field field : fields){
String type = field.getType().getCanonicalName();
if ("java.lang.String".equals(type)){
field.setAccessible(true);
Object getObject = null;
try {
getObject = field.get(object);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
if (getObject != null) {
String trim = getObject.toString().replace(" ","");
map.put(field.getName(), trim);
}
}
}
for (Field field : fields) {
if (map.get(field.getName()) != null){
String s = map.get(field.getName());
field.setAccessible(true);
try {
field.set(object, s);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
private static Field[] getAllFields(Object object) {
Class clazz = object.getClass();
List<Field[]> fieldsList = new ArrayList<>();
while (clazz != null) {
Field[] declaredFields = clazz.getDeclaredFields();
fieldsList.add(declaredFields);
clazz = clazz.getSuperclass();
}
List<Field> allFields = new ArrayList<>();
for (Field[] fields : fieldsList) {
allFields.addAll(Arrays.asList(fields));
}
return allFields.toArray(new Field[0]);
}
}
|