BeanMap这个Map类用于把一个javaBean转换为Map,在其中存储了javaBean的各个属性的setXXX方法和getXXX方法,属性的类型。
<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->
public
class
BeanMap
extends
AbstractMap
implements
Cloneable
{
private transient Objectbean; // javaBean对象
private transient HashMapreadMethods = new HashMap(); // getXXX方法集
private transient HashMapwriteMethods = new HashMap(); // setXXX方法集
private transient HashMaptypes = new HashMap(); // 成员变量类型集
public static final Object[]NULL_ARGUMENTS = {}; // 空参数集,用于通过reflection调用getXXX方法
public static HashMapdefaultTransformers = new HashMap(); // 把基本类型映射为transformer类型,后者用于将字符串转换为合适的基本型的包装类
// 默认transformer
static
{
defaultTransformers.put(Boolean.TYPE, new Transformer()
{
public Objecttransform(Objectinput)
{
return Boolean.valueOf(input.toString());
}
}
);
defaultTransformers.put(Character.TYPE, new Transformer()
{
public Objecttransform(Objectinput)
{
return new Character(input.toString().charAt( 0 ));
}
}
);
defaultTransformers.put(Byte.TYPE, new Transformer()
{
public Objecttransform(Objectinput)
{
return Byte.valueOf(input.toString());
}
}
);
defaultTransformers.put(Short.TYPE, new Transformer()
{
public Objecttransform(Objectinput)
{
return Short.valueOf(input.toString());
}
}
);
defaultTransformers.put(
Integer.TYPE,
new Transformer(){
public Objecttransform(Objectinput){
return Integer.valueOf(input.toString());
}
}
);
defaultTransformers.put(Long.TYPE, new Transformer()
{
public Objecttransform(Objectinput){
return Long.valueOf(input.toString());
}
}
);
defaultTransformers.put(Float.TYPE, new Transformer()
{
public Objecttransform(Objectinput){
return Float.valueOf(input.toString());
}
}
);
defaultTransformers.put(Double.TYPE, new Transformer()
{
public Objecttransform(Objectinput){
return Double.valueOf(input.toString());
}
}
);
}
public BeanMap(Objectbean){
this .bean = bean;
initialise();
}
public Objectclone() throws CloneNotSupportedException{
BeanMapnewMap = (BeanMap) super .clone();
if (bean == null ){ // 若底层bean不存在,则返回一个复制的空BeanMap,
return newMap;
}
ObjectnewBean = null ;
ClassbeanClass = null ;
try {
beanClass = bean.getClass(); // 底层bean的Class
newBean = beanClass.newInstance(); // 实例化一个新的bean
} catch (Exceptione){
// unabletoinstantiate
throw new CloneNotSupportedException
( " Unabletoinstantiatetheunderlyingbean/ "" +
beanClass.getName() + " / " : " +e);
}
try {
newMap.setBean(newBean);
} catch (Exceptionexception){
throw new CloneNotSupportedException
( " 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){
throw new CloneNotSupportedException
( " Unabletocopybeanvaluestoclonedbeanmap: " +
exception);
}
return newMap;
}
public void clear(){
if (bean == null ) return ;
ClassbeanClass = null ;
try {
beanClass = bean.getClass();
bean = beanClass.newInstance(); // 重新实例化,一切都回到默认状态
}
catch (Exceptione){
throw new UnsupportedOperationException( " Couldnotcreatenewinstanceofclass: " + beanClass);
}
}
public Objectget(Objectname){ // 获取指定名称属性的值
if (bean != null ){
Methodmethod = getReadMethod(name);
if (method != null ){
try {
return method.invoke(bean,NULL_ARGUMENTS);
}
catch (IllegalAccessExceptione){
logWarn(e);
}
catch (IllegalArgumentExceptione){
logWarn(e);
}
catch (InvocationTargetExceptione){
logWarn(e);
}
catch (NullPointerExceptione){
logWarn(e);
}
}
}
return null ;
}
public Objectput(Objectname,Objectvalue) throws IllegalArgumentException,ClassCastException
{ // 设置指定名称的属性的值
if (bean != null ){
ObjectoldValue = get(name); // 原来的值
Methodmethod = getWriteMethod(name);
if (method == null ){
throw new IllegalArgumentException( " 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);
throw new IllegalArgumentException(e.getMessage());
}
catch (IllegalAccessExceptione){
logInfo(e);
throw new IllegalArgumentException(e.getMessage());
}
return oldValue;
}
return null ;
}
public MethodgetReadMethod(Stringname){ // 获取指定名称属性的getXXX方法
return (Method)readMethods.get(name);
}
public MethodgetWriteMethod(Stringname){ // 获取指定名称属性的setXXX方法
return (Method)writeMethods.get(name);
}
private void initialise()
{
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 ( int i = 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);
}
}
protected static class MyMapEntry extends AbstractMapEntry
{ // BeanMap使用的Mapentry
private BeanMapowner; // 所属的Map
protected MyMapEntry(BeanMapowner,Objectkey,Objectvalue){
super (key,value);
this .owner = owner;
}
public ObjectsetValue(Objectvalue){
Objectkey = getKey();
ObjectoldValue = owner.get(key);
owner.put(key,value);
ObjectnewValue = owner.get(key);
super .setValue(newValue);
return oldValue;
}
}
protected Object[]createWriteMethodArguments(Methodmethod,Objectvalue) throws IllegalAccessException,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};
return answer;
}
catch (InvocationTargetExceptione){
logInfo(e);
throw new IllegalArgumentException(e.getMessage());
}
catch (InstantiationExceptione){
logInfo(e);
throw new IllegalArgumentException(e.getMessage());
}
}
protected ObjectconvertType(ClassnewType,Objectvalue)
throws InstantiationException,IllegalAccessException,IllegalArgumentException,InvocationTargetException{
// trycallconstructor
Class[]types = {value.getClass()};
try { // 尝试用带一个参数的构造函数进行转换
Constructorconstructor = newType.getConstructor(types);
Object[]arguments = {value};
return constructor.newInstance(arguments);
}
catch (NoSuchMethodExceptione){
// tryusingthetransformers
Transformertransformer = getTypeTransformer(newType); // 获取可用的transformer
if (transformer != null ){
return transformer.transform(value); // 转换类型
}
return value;
}
}
protected TransformergetTypeTransformer(ClassaType){
return (Transformer)defaultTransformers.get(aType);
}
}
{
private transient Objectbean; // javaBean对象
private transient HashMapreadMethods = new HashMap(); // getXXX方法集
private transient HashMapwriteMethods = new HashMap(); // setXXX方法集
private transient HashMaptypes = new HashMap(); // 成员变量类型集
public static final Object[]NULL_ARGUMENTS = {}; // 空参数集,用于通过reflection调用getXXX方法
public static HashMapdefaultTransformers = new HashMap(); // 把基本类型映射为transformer类型,后者用于将字符串转换为合适的基本型的包装类
// 默认transformer
static
{
defaultTransformers.put(Boolean.TYPE, new Transformer()
{
public Objecttransform(Objectinput)
{
return Boolean.valueOf(input.toString());
}
}
);
defaultTransformers.put(Character.TYPE, new Transformer()
{
public Objecttransform(Objectinput)
{
return new Character(input.toString().charAt( 0 ));
}
}
);
defaultTransformers.put(Byte.TYPE, new Transformer()
{
public Objecttransform(Objectinput)
{
return Byte.valueOf(input.toString());
}
}
);
defaultTransformers.put(Short.TYPE, new Transformer()
{
public Objecttransform(Objectinput)
{
return Short.valueOf(input.toString());
}
}
);
defaultTransformers.put(
Integer.TYPE,
new Transformer(){
public Objecttransform(Objectinput){
return Integer.valueOf(input.toString());
}
}
);
defaultTransformers.put(Long.TYPE, new Transformer()
{
public Objecttransform(Objectinput){
return Long.valueOf(input.toString());
}
}
);
defaultTransformers.put(Float.TYPE, new Transformer()
{
public Objecttransform(Objectinput){
return Float.valueOf(input.toString());
}
}
);
defaultTransformers.put(Double.TYPE, new Transformer()
{
public Objecttransform(Objectinput){
return Double.valueOf(input.toString());
}
}
);
}
public BeanMap(Objectbean){
this .bean = bean;
initialise();
}
public Objectclone() throws CloneNotSupportedException{
BeanMapnewMap = (BeanMap) super .clone();
if (bean == null ){ // 若底层bean不存在,则返回一个复制的空BeanMap,
return newMap;
}
ObjectnewBean = null ;
ClassbeanClass = null ;
try {
beanClass = bean.getClass(); // 底层bean的Class
newBean = beanClass.newInstance(); // 实例化一个新的bean
} catch (Exceptione){
// unabletoinstantiate
throw new CloneNotSupportedException
( " Unabletoinstantiatetheunderlyingbean/ "" +
beanClass.getName() + " / " : " +e);
}
try {
newMap.setBean(newBean);
} catch (Exceptionexception){
throw new CloneNotSupportedException
( " 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){
throw new CloneNotSupportedException
( " Unabletocopybeanvaluestoclonedbeanmap: " +
exception);
}
return newMap;
}
public void clear(){
if (bean == null ) return ;
ClassbeanClass = null ;
try {
beanClass = bean.getClass();
bean = beanClass.newInstance(); // 重新实例化,一切都回到默认状态
}
catch (Exceptione){
throw new UnsupportedOperationException( " Couldnotcreatenewinstanceofclass: " + beanClass);
}
}
public Objectget(Objectname){ // 获取指定名称属性的值
if (bean != null ){
Methodmethod = getReadMethod(name);
if (method != null ){
try {
return method.invoke(bean,NULL_ARGUMENTS);
}
catch (IllegalAccessExceptione){
logWarn(e);
}
catch (IllegalArgumentExceptione){
logWarn(e);
}
catch (InvocationTargetExceptione){
logWarn(e);
}
catch (NullPointerExceptione){
logWarn(e);
}
}
}
return null ;
}
public Objectput(Objectname,Objectvalue) throws IllegalArgumentException,ClassCastException
{ // 设置指定名称的属性的值
if (bean != null ){
ObjectoldValue = get(name); // 原来的值
Methodmethod = getWriteMethod(name);
if (method == null ){
throw new IllegalArgumentException( " 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);
throw new IllegalArgumentException(e.getMessage());
}
catch (IllegalAccessExceptione){
logInfo(e);
throw new IllegalArgumentException(e.getMessage());
}
return oldValue;
}
return null ;
}
public MethodgetReadMethod(Stringname){ // 获取指定名称属性的getXXX方法
return (Method)readMethods.get(name);
}
public MethodgetWriteMethod(Stringname){ // 获取指定名称属性的setXXX方法
return (Method)writeMethods.get(name);
}
private void initialise()
{
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 ( int i = 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);
}
}
protected static class MyMapEntry extends AbstractMapEntry
{ // BeanMap使用的Mapentry
private BeanMapowner; // 所属的Map
protected MyMapEntry(BeanMapowner,Objectkey,Objectvalue){
super (key,value);
this .owner = owner;
}
public ObjectsetValue(Objectvalue){
Objectkey = getKey();
ObjectoldValue = owner.get(key);
owner.put(key,value);
ObjectnewValue = owner.get(key);
super .setValue(newValue);
return oldValue;
}
}
protected Object[]createWriteMethodArguments(Methodmethod,Objectvalue) throws IllegalAccessException,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};
return answer;
}
catch (InvocationTargetExceptione){
logInfo(e);
throw new IllegalArgumentException(e.getMessage());
}
catch (InstantiationExceptione){
logInfo(e);
throw new IllegalArgumentException(e.getMessage());
}
}
protected ObjectconvertType(ClassnewType,Objectvalue)
throws InstantiationException,IllegalAccessException,IllegalArgumentException,InvocationTargetException{
// trycallconstructor
Class[]types = {value.getClass()};
try { // 尝试用带一个参数的构造函数进行转换
Constructorconstructor = newType.getConstructor(types);
Object[]arguments = {value};
return constructor.newInstance(arguments);
}
catch (NoSuchMethodExceptione){
// tryusingthetransformers
Transformertransformer = getTypeTransformer(newType); // 获取可用的transformer
if (transformer != null ){
return transformer.transform(value); // 转换类型
}
return value;
}
}
protected TransformergetTypeTransformer(ClassaType){
return (Transformer)defaultTransformers.get(aType);
}
}