3 changed files with 90 additions and 17 deletions
@ -0,0 +1,66 @@ |
|||
package com.epmet.commons.tools.utils; |
|||
|
|||
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]); |
|||
} |
|||
} |
Loading…
Reference in new issue