commons beanutils之使用Map封装Bean相关教程:
正文commons beanutils之使用Map封装Bean
问题
解决方案
Map beanMap = new BeanMap(person); set keys = beanMap.keySet(); BeanMap不仅仅通过Map接口公布bean的属性,它还封装了整个bean实例,这使得你可以通过put()方法改变下层bean内容.除了实现了Map接口,BeanMap也提供了一些附加方法,以获取Method对象以及bean属性的类型
clear() 通过与getBean().getClass()返回值对应的类的无参构造函数创建新的bean实例.
例: BeanMap map = new BeanMap(person); Method method = map.getWriteMethod("age"); map.put("name","John"); package test4; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Iterator; import java.util.Set; import org.apache.commons.beanutils.BeanMap; /** * 使用Map封装Bean * * @author fhd001 */ public class PropertyUtilsTest11 { public static void main(String[] args) { Person person = new Person(); person.setAge(18); person.setName("fhd001"); BeanMap beanMap = new BeanMap(person); Set keys = beanMap.keySet(); Iterator keyIterator = keys.iterator(); while(keyIterator.hasNext()){ String propertyName = (String)keyIterator.next(); System.out.println("property: " + propertyName +"\tvalue: " + beanMap.get(propertyName) + "\t\ttype: " + beanMap.getType(propertyName).toString()); } Method m1 = beanMap.getWriteMethod("age"); try { m1.invoke(person, 55); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } System.out.println("person: " + person.getAge()); } }
property: name value: fhd001 type: class java.lang.String property: age value: 18 type: int property: class value: class test4.Person type: class java.lang.Class person: 55
|
|