日期:2014-05-20 浏览次数:20926 次
package util;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class BeanMap{
private Object bean;
private Map <String,Method> readMethods;
private Map <String,Method> writeMethods;
private Map <String,Class <Object>> types;
public BeanMap(Object bean){
this.bean = bean;
initialise();
}
/**
* 为bean属性设置值
* @param name 属性名称
* @param value 属性值
* @throws Exception 当属性不存在或者属性类型不匹配时可能会抛出异常
*/
public void set(String name, Object value) throws Exception{
if(name.indexOf(".")>0){
Object obj = this.get(name.substring(0, name.indexOf(".")));
BeanMap bm = new BeanMap(obj);
bm.set(name.substring(name.indexOf(".")+1), value);
}else{
Class <Object> type = types.get(name);
Method method = writeMethods.get(name);
if(type==null || method==null){
throw new java.lang.NoSuchFieldException();
}
method.invoke(bean, value);
}
}
/**
* 取得bean的属性值
* @param name
* @return
* @throws Exception
*/
public Object get(String name) throws Exception{
if(name.indexOf(".")>0){
Object obj = this.get(name.substring(0, name.indexOf(".")));
BeanMap bm = new BeanMap(obj);
return bm.get(name.substring(name.indexOf(".")+1));
}else{
Class <Object> type = types.get(name);
Method method = readMethods.get(name);
if(type==null || method==null){
throw new java.lang.NoSuchFieldException();
}
return method.invoke(bean);
}
}
@SuppressWarnings("unchecked")
/**
* 为bean map进行初始化
*/
private void initialise()
{
readMethods = new HashMap <String,Method>();
writeMethods = new HashMap <String,Method>();
types = new HashMap <String,Class <Object>>();
if(bean == null) return;
Class beanClass = bean.getClass();
try
{
BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
if ( propertyDescriptors != null )
{
for ( int i = 0; i < propertyDescriptors.length; i++ )
{
PropertyDescriptor propertyDescriptor = propertyDescriptors[i];
if ( propertyDescriptor != null )
{
String name = propertyDescriptor.getName();
Method readMethod = propertyDescriptor.getReadMethod();
Method writeMethod = propertyDescriptor.getWriteMethod();
Class aType = propertyDescriptor.getPropertyType();