PropertyDescriptor的使用,反射的简洁使用

一、软件包 java.beans

包含与开发 beans 有关的类

二、PropertyDescriptor

JavaBean是一种特殊的类,主要用于传递数据信息,这种类中的方法主要用于访问私有的字段,且方法名符合某种命名规则。如果在两个模块之间传递信息,可以将信息封装进JavaBean中,这种对象称为“值对象”(Value Object),或“VO”。方法比较少。这些信息储存在类的私有变量中,通过set()、get()获得。

Java JDK中提供了一套API用来访问某个属性的getter/setter方法,这就是内省
构造方法:

PropertyDescriptor(String propertyName, Class<?> beanClass)
 
PropertyDescriptor(String propertyName, Class<?> beanClass, String readMethodName, String writeMethodName)
 
PropertyDescriptor(String propertyName, Method readMethod, Method writeMethod)

常用方法:

public class PropertyDescriptor extends FeatureDescriptor  
{  
    //构造方法  
    //通过调用 getFoo 和 setFoo 存取方法,为符合标准 Java 约定的属性构造一个 PropertyDescriptor  
    public PropertyDescriptor(String propertyName,  
                          Class<?> beanClass)  
                   throws IntrospectionException{}  
    //获得属性的 Class 对象  
    public Class<?> getPropertyType(){}  
  
    //获得应该用于读取属性值的方法  
    public Method getReadMethod(){}  
  
    //获得应该用于写入属性值的方法  
    public Method getWriteMethod(){}  
使用
 public static Object myObjectMapField(Class aClass, Map<String, Object> map) throws Exception {
        Object bean = aClass.newInstance();
        Set<Map.Entry<String, Object>> entrySet = map.entrySet();
        for (Map.Entry<String, Object> entry : entrySet) {
            String key = entry.getKey();
            Object value = entry.getValue();
            //创建PropertyDescriptor 对象,获取去key相同的set/get方法
            PropertyDescriptor descriptor = new PropertyDescriptor(key, bean.getClass());
            //获取set方法
            Method method = descriptor.getWriteMethod();
            //获取形参列表内容
            Object value1 = getBeanValue(value, method.getParameterTypes()[0]);
            //执行提交
            method.invoke(bean, value1);
        }
        return bean;
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值