import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class ClassNameTypeConvertor {
/**
* 根据class 获取所有的字段名 + 值
*
* @param o
* @param clz
* @return
* @throws Exception
*/
public static Map<String, Object> getValues(Object o, Class clz) throws Exception {
if (o == null || clz == null) {
throw new IllegalArgumentException("data or clz can't be empty.");
}
Map<String, Field> beanFields = getClzFields(clz);
Field field = null;
Class<?> clazz = o.getClass();
Map<String, Object> result = new HashMap<>();
for (String name : beanFields.keySet()) {
try {
field = clazz.getDeclaredField(name);
} catch (Exception e) {
//业务中大部分字段不是在父类里面
for (Class<?> tmpClz = clazz.getSuperclass(); tmpClz != Object.class; tmpClz = tmpClz.getSuperclass()) {
try {
field = tmpClz.getDeclaredField(name);
break;
} catch (Exception ignored) {
}
}
}
if (field != null) {
field.setAccessible(true);
result.put(name, field.get(o));
}
}
return result;
}
//field cache
private static ConcurrentHashMap<String, Map<String, Field>> CACHED_CLZ_FIELDS = new ConcurrentHashMap<>();
private static Map<String, Field> getClzFields(Class clz) {
Map<String, Field> beanFields = CACHED_CLZ_FIELDS.get(clz.getName());
if (beanFields == null || beanFields.size() <= 0) {
beanFields = getAllFieldsForBean(clz);
CACHED_CLZ_FIELDS.putIfAbsent(clz.getName(), beanFields);
beanFields = CACHED_CLZ_FIELDS.get(clz.getName());
}
return beanFields;
}
private static final String FINAL_PARENT = "java.lang.object";
/**
* 取类的所有属性, 包括父类
*
* @param clz
* @return
*/
private static Map<String, Field> getAllFieldsForBean(Class clz) {
Map<String, Field> result = new HashMap<>();
Class tmpClz = clz;
while (tmpClz != null && !tmpClz.getName().toLowerCase().equals(FINAL_PARENT)) {
for (Field field : tmpClz.getDeclaredFields()) {
field.setAccessible(true);
int modifiers = field.getModifiers();
if (modifiers == Modifier.PUBLIC || modifiers == Modifier.PRIVATE || modifiers == Modifier.PROTECTED) {
result.put(field.getName(), field);
}
}
tmpClz = tmpClz.getSuperclass();
}
return result;
}
}