基于内省机制实现BeanUtils工具类

相关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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。