Jdk bean转map
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.beans.Transient;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class Tools {
public static Map<String, Object> beanToMap(Object obj) {
try {
Map<String, Object> map = new HashMap();
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
if (key.compareToIgnoreCase("class") == 0) {
continue;
}
Method getter = property.getReadMethod();
Transient annotation = getter.getAnnotation(Transient.class);
if (annotation == null) {
Object value = getter != null ? getter.invoke(obj) : null;
map.put(key, value);
}
}
return map;
} catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) {
throw new IllegalArgumentException(e.getMessage());
}
}
}
apache bean和map互转
import org.apache.commons.beanutils.BeanUtils;
private Map beanToMap(Object obj) {
try {
return BeanUtils.describe(obj);
} catch (IllegalAccessException | InvocationTargetException
| NoSuchMethodException e) {
e.printStackTrace();
}
return null;
}
private List<?> mapToBean(List<Map<String, Object>> data, Class<?> clazz) {
List<Object> list = new ArrayList<>();
try {
for (int i = 0; i < data.size(); i++) {
Object newInstance = clazz.newInstance();
Map<String, Object> map = data.get(i);
BeanUtils.populate(newInstance, map);
list.add(newInstance);
}
return list;
} catch (Exception e) {
}
return null;
}
还没有评论,来说两句吧...