分享

commons beanutils之使用Map封装Bean

 陈湖雨_毓 2012-03-12

commons beanutils之使用Map封装Bean

 

正文

 

commons beanutils之使用Map封装Bean

 

问题
你需要将bean的属性转入Map,并以对待Map中元素的方式处理bean属性.

 

解决方案
可使用BeanMap类封装任何bean.该Map通过内省机制提供了对bean属性的访问,使得其看上去像是Map中成对的键与值.


如:
Person person = new Person();
person.setName("Jim");
person.setAge(23);
person.setOccupation("Developer");

Map 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 + ",value: " + beanMap.get(propertyName)+",type:"+beanMap.getType(propertyName).toString());
}

BeanMap不仅仅通过Map接口公布bean的属性,它还封装了整个bean实例,这使得你可以通过put()方法改变下层bean内容.除了实现了Map接口,BeanMap也提供了一些附加方法,以获取Method对象以及bean属性的类型

 

clear()           通过与getBean().getClass()返回值对应的类的无参构造函数创建新的bean实例.
clone()           可能的话,创建另一个BeanMap实例,并将原BeanMap中已封装的bean拷贝进去.
setBean(Object bean)    使BeanMap实例封装一个给定的bean.
getType(String name)    检索指定bean属性的类型
getReadMethod(String name) 检索指定属性对应的读(getter)方法的Method对象.
getWriteMethod(String name) 检索指定属性对应的写(setter)方法的Method对象.

 

例:
Person person = new Person();
person.setName("Todd");
person.setAge(34);
person.setOccupation("Record Collector");

BeanMap map = new BeanMap(person);

Method method = map.getWriteMethod("age");
nethod.invoke(person,12);

map.put("name","John");
Class type = map.getType("age");
map.setBean(null);

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

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多