BeanMap这个Map类用于把一个javaBean转换为Map,在其中存储了javaBean的各个属性的setXXX方法和getXXX方法,属性的类型。
<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->publicclassBeanMapextendsAbstractMapimplementsCloneable
{
privatetransientObjectbean;//javaBean对象
privatetransientHashMapreadMethods=newHashMap();//getXXX方法集
privatetransientHashMapwriteMethods=newHashMap();//setXXX方法集
privatetransientHashMaptypes=newHashMap();//成员变量类型集
publicstaticfinalObject[]NULL_ARGUMENTS={};//空参数集,用于通过reflection调用getXXX方法
publicstaticHashMapdefaultTransformers=newHashMap();//把基本类型映射为transformer类型,后者用于将字符串转换为合适的基本型的包装类
//默认transformer
static
{
defaultTransformers.put(Boolean.TYPE,newTransformer()
{
publicObjecttransform(Objectinput)
{
returnBoolean.valueOf(input.toString());
}
}
);
defaultTransformers.put(Character.TYPE,newTransformer()
{
publicObjecttransform(Objectinput)
{
returnnewCharacter(input.toString().charAt(0));
}
}
);
defaultTransformers.put(Byte.TYPE,newTransformer()
{
publicObjecttransform(Objectinput)
{
returnByte.valueOf(input.toString());
}
}
);
defaultTransformers.put(Short.TYPE,newTransformer()
{
publicObjecttransform(Objectinput)
{
returnShort.valueOf(input.toString());
}
}
);
defaultTransformers.put(
Integer.TYPE,
newTransformer(){
publicObjecttransform(Objectinput){
returnInteger.valueOf(input.toString());
}
}
);
defaultTransformers.put(Long.TYPE,newTransformer()
{
publicObjecttransform(Objectinput){
returnLong.valueOf(input.toString());
}
}
);
defaultTransformers.put(Float.TYPE,newTransformer()
{
publicObjecttransform(Objectinput){
returnFloat.valueOf(input.toString());
}
}
);
defaultTransformers.put(Double.TYPE,newTransformer()
{
publicObjecttransform(Objectinput){
returnDouble.valueOf(input.toString());
}
}
);
}
publicBeanMap(Objectbean){
this.bean=bean;
initialise();
}
publicObjectclone()throwsCloneNotSupportedException{
BeanMapnewMap=(BeanMap)super.clone();
if(bean==null){//若底层bean不存在,则返回一个复制的空BeanMap,
returnnewMap;
}
ObjectnewBean=null;
ClassbeanClass=null;
try{
beanClass=bean.getClass();//底层bean的Class
newBean=beanClass.newInstance();//实例化一个新的bean
}catch(Exceptione){
//unabletoinstantiate
thrownewCloneNotSupportedException
("Unabletoinstantiatetheunderlyingbean/""+
beanClass.getName()+"/":"+e);
}
try{
newMap.setBean(newBean);
}catch(Exceptionexception){
thrownewCloneNotSupportedException
("Unabletosetbeanintheclonedbeanmap:"+
exception);
}
try{
//复制所有可读写的属性
IteratorreadableKeys=readMethods.keySet().iterator();
while(readableKeys.hasNext()){
Objectkey=readableKeys.next();//属性名称
if(getWriteMethod(key)!=null){
newMap.put(key,get(key));//放入到新BeanMap中
}
}
}catch(Exceptionexception){
thrownewCloneNotSupportedException
("Unabletocopybeanvaluestoclonedbeanmap:"+
exception);
}
returnnewMap;
}
publicvoidclear(){
if(bean==null)return;
ClassbeanClass=null;
try{
beanClass=bean.getClass();
bean=beanClass.newInstance();//重新实例化,一切都回到默认状态
}
catch(Exceptione){
thrownewUnsupportedOperationException("Couldnotcreatenewinstanceofclass:"+beanClass);
}
}
publicObjectget(Objectname){//获取指定名称属性的值
if(bean!=null){
Methodmethod=getReadMethod(name);
if(method!=null){
try{
returnmethod.invoke(bean,NULL_ARGUMENTS);
}
catch(IllegalAccessExceptione){
logWarn(e);
}
catch(IllegalArgumentExceptione){
logWarn(e);
}
catch(InvocationTargetExceptione){
logWarn(e);
}
catch(NullPointerExceptione){
logWarn(e);
}
}
}
returnnull;
}
publicObjectput(Objectname,Objectvalue)throwsIllegalArgumentException,ClassCastException
{//设置指定名称的属性的值
if(bean!=null){
ObjectoldValue=get(name);//原来的值
Methodmethod=getWriteMethod(name);
if(method==null){
thrownewIllegalArgumentException("Thebeanoftype:"+bean.getClass().getName()+"hasnopropertycalled:"+name);
}
try{
Object[]arguments=createWriteMethodArguments(method,value);//转换参数
method.invoke(bean,arguments);//设置新值
ObjectnewValue=get(name);//获取新设置的值
firePropertyChange(name,oldValue,newValue);//fire属性值改变事件
}
catch(InvocationTargetExceptione){
logInfo(e);
thrownewIllegalArgumentException(e.getMessage());
}
catch(IllegalAccessExceptione){
logInfo(e);
thrownewIllegalArgumentException(e.getMessage());
}
returnoldValue;
}
returnnull;
}
publicMethodgetReadMethod(Stringname){//获取指定名称属性的getXXX方法
return(Method)readMethods.get(name);
}
publicMethodgetWriteMethod(Stringname){//获取指定名称属性的setXXX方法
return(Method)writeMethods.get(name);
}
privatevoidinitialise()
{
if(getBean()==null)return;
ClassbeanClass=getBean().getClass();//bean的Class
try
{
//BeanInfobeanInfo=Introspector.getBeanInfo(bean,null);
BeanInfobeanInfo=Introspector.getBeanInfo(beanClass);//bean的信息
PropertyDescriptor[]propertyDescriptors=beanInfo.getPropertyDescriptors();
if(propertyDescriptors!=null)
{
for(inti=0;i<propertyDescriptors.length;i++)
{
PropertyDescriptorpropertyDescriptor=propertyDescriptors[i];
if(propertyDescriptor!=null)
{
Stringname=propertyDescriptor.getName();//属性名称
MethodreadMethod=propertyDescriptor.getReadMethod();//getXXX方法
MethodwriteMethod=propertyDescriptor.getWriteMethod();//setXXX方法
ClassaType=propertyDescriptor.getPropertyType();//属性类型
if(readMethod!=null){
readMethods.put(name,readMethod);//保存到getXXX集合
}
if(writeMethod!=null){
writeMethods.put(name,writeMethod);//保存到setXXX集合
}
types.put(name,aType);//保存属性类型
}
}
}
}
catch(IntrospectionExceptione){
logWarn(e);
}
}
protectedstaticclassMyMapEntryextendsAbstractMapEntry
{//BeanMap使用的Mapentry
privateBeanMapowner;//所属的Map
protectedMyMapEntry(BeanMapowner,Objectkey,Objectvalue){
super(key,value);
this.owner=owner;
}
publicObjectsetValue(Objectvalue){
Objectkey=getKey();
ObjectoldValue=owner.get(key);
owner.put(key,value);
ObjectnewValue=owner.get(key);
super.setValue(newValue);
returnoldValue;
}
}
protectedObject[]createWriteMethodArguments(Methodmethod,Objectvalue)throwsIllegalAccessException,ClassCastException
{
try
{
if(value!=null)
{
Class[]types=method.getParameterTypes();//setXXX方法的参数类型
if(types!=null&&types.length>0)
{
ClassparamType=types[0];
if(!paramType.isAssignableFrom(value.getClass()))
{
value=convertType(paramType,value);//把新参数转换为setXXX方法的参数类型
}
}
}
Object[]answer={value};
returnanswer;
}
catch(InvocationTargetExceptione){
logInfo(e);
thrownewIllegalArgumentException(e.getMessage());
}
catch(InstantiationExceptione){
logInfo(e);
thrownewIllegalArgumentException(e.getMessage());
}
}
protectedObjectconvertType(ClassnewType,Objectvalue)
throwsInstantiationException,IllegalAccessException,IllegalArgumentException,InvocationTargetException{
//trycallconstructor
Class[]types={value.getClass()};
try{//尝试用带一个参数的构造函数进行转换
Constructorconstructor=newType.getConstructor(types);
Object[]arguments={value};
returnconstructor.newInstance(arguments);
}
catch(NoSuchMethodExceptione){
//tryusingthetransformers
Transformertransformer=getTypeTransformer(newType);//获取可用的transformer
if(transformer!=null){
returntransformer.transform(value);//转换类型
}
returnvalue;
}
}
protectedTransformergetTypeTransformer(ClassaType){
return(Transformer)defaultTransformers.get(aType);
}
}
{
privatetransientObjectbean;//javaBean对象
privatetransientHashMapreadMethods=newHashMap();//getXXX方法集
privatetransientHashMapwriteMethods=newHashMap();//setXXX方法集
privatetransientHashMaptypes=newHashMap();//成员变量类型集
publicstaticfinalObject[]NULL_ARGUMENTS={};//空参数集,用于通过reflection调用getXXX方法
publicstaticHashMapdefaultTransformers=newHashMap();//把基本类型映射为transformer类型,后者用于将字符串转换为合适的基本型的包装类
//默认transformer
static
{
defaultTransformers.put(Boolean.TYPE,newTransformer()
{
publicObjecttransform(Objectinput)
{
returnBoolean.valueOf(input.toString());
}
}
);
defaultTransformers.put(Character.TYPE,newTransformer()
{
publicObjecttransform(Objectinput)
{
returnnewCharacter(input.toString().charAt(0));
}
}
);
defaultTransformers.put(Byte.TYPE,newTransformer()
{
publicObjecttransform(Objectinput)
{
returnByte.valueOf(input.toString());
}
}
);
defaultTransformers.put(Short.TYPE,newTransformer()
{
publicObjecttransform(Objectinput)
{
returnShort.valueOf(input.toString());
}
}
);
defaultTransformers.put(
Integer.TYPE,
newTransformer(){
publicObjecttransform(Objectinput){
returnInteger.valueOf(input.toString());
}
}
);
defaultTransformers.put(Long.TYPE,newTransformer()
{
publicObjecttransform(Objectinput){
returnLong.valueOf(input.toString());
}
}
);
defaultTransformers.put(Float.TYPE,newTransformer()
{
publicObjecttransform(Objectinput){
returnFloat.valueOf(input.toString());
}
}
);
defaultTransformers.put(Double.TYPE,newTransformer()
{
publicObjecttransform(Objectinput){
returnDouble.valueOf(input.toString());
}
}
);
}
publicBeanMap(Objectbean){
this.bean=bean;
initialise();
}
publicObjectclone()throwsCloneNotSupportedException{
BeanMapnewMap=(BeanMap)super.clone();
if(bean==null){//若底层bean不存在,则返回一个复制的空BeanMap,
returnnewMap;
}
ObjectnewBean=null;
ClassbeanClass=null;
try{
beanClass=bean.getClass();//底层bean的Class
newBean=beanClass.newInstance();//实例化一个新的bean
}catch(Exceptione){
//unabletoinstantiate
thrownewCloneNotSupportedException
("Unabletoinstantiatetheunderlyingbean/""+
beanClass.getName()+"/":"+e);
}
try{
newMap.setBean(newBean);
}catch(Exceptionexception){
thrownewCloneNotSupportedException
("Unabletosetbeanintheclonedbeanmap:"+
exception);
}
try{
//复制所有可读写的属性
IteratorreadableKeys=readMethods.keySet().iterator();
while(readableKeys.hasNext()){
Objectkey=readableKeys.next();//属性名称
if(getWriteMethod(key)!=null){
newMap.put(key,get(key));//放入到新BeanMap中
}
}
}catch(Exceptionexception){
thrownewCloneNotSupportedException
("Unabletocopybeanvaluestoclonedbeanmap:"+
exception);
}
returnnewMap;
}
publicvoidclear(){
if(bean==null)return;
ClassbeanClass=null;
try{
beanClass=bean.getClass();
bean=beanClass.newInstance();//重新实例化,一切都回到默认状态
}
catch(Exceptione){
thrownewUnsupportedOperationException("Couldnotcreatenewinstanceofclass:"+beanClass);
}
}
publicObjectget(Objectname){//获取指定名称属性的值
if(bean!=null){
Methodmethod=getReadMethod(name);
if(method!=null){
try{
returnmethod.invoke(bean,NULL_ARGUMENTS);
}
catch(IllegalAccessExceptione){
logWarn(e);
}
catch(IllegalArgumentExceptione){
logWarn(e);
}
catch(InvocationTargetExceptione){
logWarn(e);
}
catch(NullPointerExceptione){
logWarn(e);
}
}
}
returnnull;
}
publicObjectput(Objectname,Objectvalue)throwsIllegalArgumentException,ClassCastException
{//设置指定名称的属性的值
if(bean!=null){
ObjectoldValue=get(name);//原来的值
Methodmethod=getWriteMethod(name);
if(method==null){
thrownewIllegalArgumentException("Thebeanoftype:"+bean.getClass().getName()+"hasnopropertycalled:"+name);
}
try{
Object[]arguments=createWriteMethodArguments(method,value);//转换参数
method.invoke(bean,arguments);//设置新值
ObjectnewValue=get(name);//获取新设置的值
firePropertyChange(name,oldValue,newValue);//fire属性值改变事件
}
catch(InvocationTargetExceptione){
logInfo(e);
thrownewIllegalArgumentException(e.getMessage());
}
catch(IllegalAccessExceptione){
logInfo(e);
thrownewIllegalArgumentException(e.getMessage());
}
returnoldValue;
}
returnnull;
}
publicMethodgetReadMethod(Stringname){//获取指定名称属性的getXXX方法
return(Method)readMethods.get(name);
}
publicMethodgetWriteMethod(Stringname){//获取指定名称属性的setXXX方法
return(Method)writeMethods.get(name);
}
privatevoidinitialise()
{
if(getBean()==null)return;
ClassbeanClass=getBean().getClass();//bean的Class
try
{
//BeanInfobeanInfo=Introspector.getBeanInfo(bean,null);
BeanInfobeanInfo=Introspector.getBeanInfo(beanClass);//bean的信息
PropertyDescriptor[]propertyDescriptors=beanInfo.getPropertyDescriptors();
if(propertyDescriptors!=null)
{
for(inti=0;i<propertyDescriptors.length;i++)
{
PropertyDescriptorpropertyDescriptor=propertyDescriptors[i];
if(propertyDescriptor!=null)
{
Stringname=propertyDescriptor.getName();//属性名称
MethodreadMethod=propertyDescriptor.getReadMethod();//getXXX方法
MethodwriteMethod=propertyDescriptor.getWriteMethod();//setXXX方法
ClassaType=propertyDescriptor.getPropertyType();//属性类型
if(readMethod!=null){
readMethods.put(name,readMethod);//保存到getXXX集合
}
if(writeMethod!=null){
writeMethods.put(name,writeMethod);//保存到setXXX集合
}
types.put(name,aType);//保存属性类型
}
}
}
}
catch(IntrospectionExceptione){
logWarn(e);
}
}
protectedstaticclassMyMapEntryextendsAbstractMapEntry
{//BeanMap使用的Mapentry
privateBeanMapowner;//所属的Map
protectedMyMapEntry(BeanMapowner,Objectkey,Objectvalue){
super(key,value);
this.owner=owner;
}
publicObjectsetValue(Objectvalue){
Objectkey=getKey();
ObjectoldValue=owner.get(key);
owner.put(key,value);
ObjectnewValue=owner.get(key);
super.setValue(newValue);
returnoldValue;
}
}
protectedObject[]createWriteMethodArguments(Methodmethod,Objectvalue)throwsIllegalAccessException,ClassCastException
{
try
{
if(value!=null)
{
Class[]types=method.getParameterTypes();//setXXX方法的参数类型
if(types!=null&&types.length>0)
{
ClassparamType=types[0];
if(!paramType.isAssignableFrom(value.getClass()))
{
value=convertType(paramType,value);//把新参数转换为setXXX方法的参数类型
}
}
}
Object[]answer={value};
returnanswer;
}
catch(InvocationTargetExceptione){
logInfo(e);
thrownewIllegalArgumentException(e.getMessage());
}
catch(InstantiationExceptione){
logInfo(e);
thrownewIllegalArgumentException(e.getMessage());
}
}
protectedObjectconvertType(ClassnewType,Objectvalue)
throwsInstantiationException,IllegalAccessException,IllegalArgumentException,InvocationTargetException{
//trycallconstructor
Class[]types={value.getClass()};
try{//尝试用带一个参数的构造函数进行转换
Constructorconstructor=newType.getConstructor(types);
Object[]arguments={value};
returnconstructor.newInstance(arguments);
}
catch(NoSuchMethodExceptione){
//tryusingthetransformers
Transformertransformer=getTypeTransformer(newType);//获取可用的transformer
if(transformer!=null){
returntransformer.transform(value);//转换类型
}
returnvalue;
}
}
protectedTransformergetTypeTransformer(ClassaType){
return(Transformer)defaultTransformers.get(aType);
}
}
本文介绍了一个用于转换JavaBean为Map的实用工具BeanMap。BeanMap能够将JavaBean对象的属性映射为Map结构,便于数据操作。文章详细阐述了BeanMap的内部实现,包括属性的读写方法和类型转换等关键功能。
2245

被折叠的 条评论
为什么被折叠?



