Java-MVC-内省反射2-封装MyBeanUtils

来源:互联网 发布:联通宽带网络测速 编辑:程序博客网 时间:2024/06/06 04:03

【Java中的内省】:
用来获得JavaBean的属性及属性的get或set方法
JavaBean就是一个特定格式的Java类:

需要提供无参数的构造方法
属性私有
对私有的属性提供public的GET、Set方法

public class MyBeanUtils {    public static void populate(Object object,Map<String, String[] >map) throws Exception{//      获得类的所有属性的名称        BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass());//      获得类中的所有属性:        PropertyDescriptor[] propertyDescriptor = beanInfo.getPropertyDescriptors();        for (PropertyDescriptor propertyDescriptor2 : propertyDescriptor) {            if (map.containsKey(propertyDescriptor2.getName())) {                Method method = propertyDescriptor2.getWriteMethod();//              执行Set方法                method.invoke(object, map.get(propertyDescriptor2.getName())[0]);            }        }    }}   
原创粉丝点击