BeanMap这个Map类用于把一个javaBean转换为Map,在其中存储了javaBean的各个属性的setXXX方法和getXXX方法,属性的类型。
复制代码
public class BeanMap extends AbstractMap implements Cloneable 
{
private transient Object bean;//javaBean对象
private transient HashMap readMethods = new HashMap();//getXXX方法集
private transient HashMap writeMethods = new HashMap();//setXXX方法集
private transient HashMap types = new HashMap();//成员变量类型集
public static final Object[] NULL_ARGUMENTS = {};//空参数集,用于通过reflection调用getXXX方法
public static HashMap defaultTransformers = new HashMap();//把基本类型映射为transformer类型,后者用于将字符串转换为合适的基本型的包装类
//默认transformer
static 
{
defaultTransformers.put( Boolean.TYPE, new Transformer() 
{
public Object transform( Object input ) 
{
return Boolean.valueOf( input.toString() );
}
}
);
defaultTransformers.put( Character.TYPE, new Transformer() 
{
public Object transform( Object input ) 
{
return new Character( input.toString().charAt( 0 ) );
}
}
);
defaultTransformers.put( Byte.TYPE, new Transformer() 
{
public Object transform( Object input ) 
{
return Byte.valueOf( input.toString() );
}
}
);
defaultTransformers.put( Short.TYPE, new Transformer() 
{
public Object transform( Object input ) 
{
return Short.valueOf( input.toString() );
}
}
);
defaultTransformers.put( 
Integer.TYPE, 
new Transformer() {
public Object transform( Object input ) {
return Integer.valueOf( input.toString() );
}
}
);
defaultTransformers.put( Long.TYPE, new Transformer() 
{
public Object transform( Object input ) {
return Long.valueOf( input.toString() );
}
}
);
defaultTransformers.put( Float.TYPE, new Transformer() 
{
public Object transform( Object input ) {
return Float.valueOf( input.toString() );
}
}
);
defaultTransformers.put( Double.TYPE, new Transformer() 
{
public Object transform( Object input ) {
return Double.valueOf( input.toString() );
}
}
);
}
public BeanMap(Object bean) {
this.bean = bean;
initialise();
}
public Object clone() throws CloneNotSupportedException {
BeanMap newMap = (BeanMap)super.clone();
if(bean == null) {//若底层bean不存在,则返回一个复制的空BeanMap,
return newMap;
}
Object newBean = null;            
Class beanClass = null;
try {
beanClass = bean.getClass();//底层bean的Class
newBean = beanClass.newInstance();//实例化一个新的bean
} catch (Exception e) {
// unable to instantiate
throw new CloneNotSupportedException
("Unable to instantiate the underlying bean \"" +
beanClass.getName() + "\": " + e);
}
try {
newMap.setBean(newBean);
} catch (Exception exception) {
throw new CloneNotSupportedException
("Unable to set bean in the cloned bean map: " + 
exception);
}
try {
//复制所有可读写的属性
Iterator readableKeys = readMethods.keySet().iterator();
while(readableKeys.hasNext()) {
Object key = readableKeys.next();//属性名称
if(getWriteMethod(key) != null) {
newMap.put(key, get(key));//放入到新BeanMap中
}
}
} catch (Exception exception) {
throw new CloneNotSupportedException
("Unable to copy bean values to cloned bean map: " +
exception);
}
return newMap;
}
public void clear() {
if(bean == null) return;
Class beanClass = null;
try {
beanClass = bean.getClass();
bean = beanClass.newInstance();//重新实例化,一切都回到默认状态
}
catch (Exception e) {
throw new UnsupportedOperationException( "Could not create new instance of class: " + beanClass );
}
}
public Object get(Object name) {//获取指定名称属性的值
if ( bean != null ) {
Method method = getReadMethod( name );
if ( method != null ) {
try {
return method.invoke( bean, NULL_ARGUMENTS );
}
catch (  IllegalAccessException e ) {
logWarn( e );
}
catch ( IllegalArgumentException e ) {
logWarn(  e );
}
catch ( InvocationTargetException e ) {
logWarn(  e );
}
catch ( NullPointerException e ) {
logWarn(  e );
}
}
}
return null;
}
public Object put(Object name, Object value) throws IllegalArgumentException, ClassCastException
{//设置指定名称的属性的值
if ( bean != null ) {
Object oldValue = get( name );//原来的值
Method method = getWriteMethod( name );
if ( method == null ) {
throw new IllegalArgumentException( "The bean of type: "+ bean.getClass().getName() + " has no property called: " + name );
}
try {
Object[] arguments = createWriteMethodArguments( method, value );//转换参数
method.invoke( bean, arguments );//设置新值
Object newValue = get( name );//获取新设置的值 
firePropertyChange( name, oldValue, newValue );//fire属性值改变事件
}
catch ( InvocationTargetException e ) {
logInfo( e );
throw new IllegalArgumentException( e.getMessage() );
}
catch ( IllegalAccessException e ) {
logInfo( e );
throw new IllegalArgumentException( e.getMessage() );
}
return oldValue;
}
return null;
}
public Method getReadMethod(String name) {//获取指定名称属性的getXXX方法
return (Method) readMethods.get(name);
}
public Method getWriteMethod(String name) {//获取指定名称属性的setXXX方法
return (Method) writeMethods.get(name);
}
private void initialise() 
{
if(getBean() == null) return;
Class  beanClass = getBean().getClass();//bean的Class
try 
{
//BeanInfo beanInfo = Introspector.getBeanInfo( bean, null );
BeanInfo beanInfo = Introspector.getBeanInfo( beanClass );//bean的信息
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();//getXXX方法
Method writeMethod = propertyDescriptor.getWriteMethod();//setXXX方法
Class aType = propertyDescriptor.getPropertyType();//属性类型
if ( readMethod != null ) {
readMethods.put( name, readMethod );//保存到getXXX集合
}
if ( writeMethod != null ) {
writeMethods.put( name, writeMethod );//保存到setXXX集合
}
types.put( name, aType );//保存属性类型
}
}
}
}
catch ( IntrospectionException e ) {
logWarn(  e );
}
}
protected static class MyMapEntry extends AbstractMapEntry 
{//BeanMap使用的Map entry        
private BeanMap owner;//所属的Map
protected MyMapEntry( BeanMap owner, Object key, Object value ) {
super( key, value );
this.owner = owner;
}
public Object setValue(Object value) {
Object key = getKey();
Object oldValue = owner.get( key );
owner.put( key, value );
Object newValue = owner.get( key );
super.setValue( newValue );
return oldValue;
}
}
protected Object[] createWriteMethodArguments( Method method, Object value ) throws IllegalAccessException, ClassCastException 
{            
try 
{
if ( value != null ) 
{
Class[] types = method.getParameterTypes();//setXXX方法的参数类型
if ( types != null && types.length > 0 ) 
{
Class paramType = types[0];
if ( ! paramType.isAssignableFrom( value.getClass() ) ) 
{
value = convertType( paramType, value );//把新参数转换为setXXX方法的参数类型
}
}
}
Object[] answer = { value };
return answer;
}
catch ( InvocationTargetException e ) {
logInfo( e );
throw new IllegalArgumentException( e.getMessage() );
}
catch ( InstantiationException e ) {
logInfo( e );
throw new IllegalArgumentException( e.getMessage() );
}
}
protected Object convertType( Class newType, Object value ) 
throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
// try call constructor
Class[] types = { value.getClass() };
try {//尝试用带一个参数的构造函数进行转换
Constructor constructor = newType.getConstructor( types );        
Object[] arguments = { value };
return constructor.newInstance( arguments );
}
catch ( NoSuchMethodException e ) {
// try using the transformers
Transformer transformer = getTypeTransformer( newType );//获取可用的transformer
if ( transformer != null ) {
return transformer.transform( value );//转换类型
}
return value;
}
}
protected Transformer getTypeTransformer( Class aType ) {
return (Transformer) defaultTransformers.get( aType );
}
}
复制代码
本文转自Phinecos(洞庭散人)博客园博客,原文链接:http://www.cnblogs.com/phinecos/archive/2008/12/20/1358910.html,如需转载请自行联系原作者

Commons Collections学习笔记(四)相关推荐

  1. C#可扩展编程之MEF学习笔记(四):见证奇迹的时刻

    前面三篇讲了MEF的基础和基本到导入导出方法,下面就是见证MEF真正魅力所在的时刻.如果没有看过前面的文章,请到我的博客首页查看. 前面我们都是在一个项目中写了一个类来测试的,但实际开发中,我们往往要 ...

  2. IOS学习笔记(四)之UITextField和UITextView控件学习

    IOS学习笔记(四)之UITextField和UITextView控件学习(博客地址:http://blog.csdn.net/developer_jiangqq) Author:hmjiangqq ...

  3. RabbitMQ学习笔记四:RabbitMQ命令(附疑难问题解决)

    RabbitMQ学习笔记四:RabbitMQ命令(附疑难问题解决) 参考文章: (1)RabbitMQ学习笔记四:RabbitMQ命令(附疑难问题解决) (2)https://www.cnblogs. ...

  4. JSP学习笔记(四十九):抛弃POI,使用iText生成Word文档

    POI操作excel的确很优秀,操作word的功能却不敢令人恭维.我们可以利用iText生成rtf文档,扩展名使用doc即可. 使用iText生成rtf,除了iText的包外,还需要额外的一个支持rt ...

  5. Ethernet/IP 学习笔记四

    Ethernet/IP 学习笔记四 EtherNet/IP Quick Start for Vendors Handbook (PUB213R0): https://www.odva.org/Port ...

  6. OpenCV学习笔记四-image的一些整体操作

    title: OpenCV学习笔记四-image的一些整体操作 categories: 编程 date: 2019-08-08 12:50:47 tags: OpenCV image的一些操作 sP4 ...

  7. 吴恩达《机器学习》学习笔记四——单变量线性回归(梯度下降法)代码

    吴恩达<机器学习>学习笔记四--单变量线性回归(梯度下降法)代码 一.问题介绍 二.解决过程及代码讲解 三.函数解释 1. pandas.read_csv()函数 2. DataFrame ...

  8. esp8266舵机驱动_arduino开发ESP8266学习笔记四—–舵机

    arduino开发ESP8266学习笔记四-–舵机 使用时发现会有ESP8266掉电的情况,应该是板上的稳压芯片的限流导致的,观测波形,发现当舵机运转时,电源线3.3V不再是稳定的3.3V,大概是在3 ...

  9. mysql新增表字段回滚_MySql学习笔记四

    MySql学习笔记四 5.3.数据类型 数值型 整型 小数 定点数 浮点数 字符型 较短的文本:char, varchar 较长的文本:text, blob(较长的二进制数据) 日期型 原则:所选择类 ...

最新文章

  1. java initcause_Java 异常
  2. SSH服务理论+实践
  3. 【研究院】滴滴研究院,都在做什么
  4. AngularJS学习笔记一:简单入门
  5. ant design pro取消登录_JeecgBoot实战按需加载 Ant-Design-Vue和Icon
  6. linq 解决winForm中控件CheckedListBox操作的问题。(转载)
  7. java怎么接收前端请求_前端json post 请求 后端怎么接收
  8. 趋势 | AI技能排行榜:TensorFlow热度飙升,Python最火
  9. Zend Studio 实用快捷键一览表
  10. 隐马尔可夫模型(HMM)****
  11. python对日期型数据排序_如何对日期执行数学运算并用Python对它们进行排序?
  12. tesseract 4.0 ocr图像识别利器,可识别文字。图片越高清越准确
  13. 【转载】NBU异机恢复oracle
  14. my first d3d application 哈哈哈。
  15. js去除字符串空格(空白符)
  16. 基于 RSSHub 搭建 RSS 生成器(群晖 Docker)
  17. 年审是当月还是当天_车辆年审时间当月到当月办理可以吗
  18. 用CMD命令查看局域网电脑IP地址,电脑名称及MAC地址
  19. 树莓派电脑虚拟机3设备连接
  20. 羊毛出在狗身上让猪来买单 - 智能音箱背后的平台经济

热门文章

  1. Visual Studio生成汇编列表文件(listing file)
  2. C/C++ realloc()函数解析
  3. 设置SSH通过密钥登录
  4. PySpider问题记录http599
  5. bzoj1562 [NOI2009]变换序列
  6. ssh : how to add hostkey to “know_hosts”
  7. bizagi simulation 仿真学习
  8. Mysql对用户操作加审计功能——高级版
  9. C#中一些常用的方法使用
  10. win2003下如何自动备份MySQL数据库