相关API
java.beans.Introspector 1.1
- static BeanInfo getBeanInfo(Class<?> beanClass)
获取指定类的bean信息
java.beans.BeanInfo 1.1
- PropertyDescriptor[] getpropertyDescriptors()
返回bean属性的描述符。如果返回null,则表示应该用命名规则来查找属性。
java.beans.PropertyDescriptor 1.1
- Method getReadMethod()
- Method getWriteMethod()
返回获取和设置属性的方法。
java.beans.FeatureDescriptor 1.1
- String getName()
获取该特性在程序中的名字。(属性/方法/事件的编程名称)
java.lang.reflect
- Object invoke(Object obj,Object... args)
对带有指定参数的指定对象调用由此 Method 对象表示的底层方法。
java.lang.Class<T>
- T newInstance()
创建此 Class 对象所表示的类的一个新实例。
代码
public class BeanUtils {
private BeanUtils() {
}
public static <T> T mapToBean(Map<String, Object> map, Class<T> clzss) throws Exception {
T instance = clzss.newInstance();
BeanInfo beanInfo = Introspector.getBeanInfo(clzss, Object.class);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
propertyDescriptor.getWriteMethod().invoke(instance, map.get(propertyDescriptor.getName()));
}
return instance;
}
public static Map<String,Object> beanToMap(Object object) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
Map<String, Object> map = new HashMap<>();
BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass(), Object.class);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
Object invoke = propertyDescriptor.getReadMethod().invoke(object);
map.put(propertyDescriptor.getName(), invoke);
}
return map;
}
}