Apache Commons Beanutils为开源软件,可在Apache官网http://commons.apache.org/proper/commons-beanutils/download_beanutils.cgi下载,使用它还需另一个Apache开源软件Apache
Commons Logging,可在Apache官网http://commons.apache.org/proper/commons-logging/download_logging.cgi下载,我使用的是commons-beanutils-1.9.1-bin.zip和commons-logging-1.1.3-bin.zip

public class User {
private String name;
private Integer age;
private boolean single;
private Map<Integer,Integer> map; public User(){} public User(String name,Integer age,boolean single,
Map<Integer,Integer> map){
this.name = name;
this.age = age;
this.single = single;
this.map = map;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public boolean isSingle() {
return single;
} public void setSingle(boolean single) {
this.single = single;
} public Map<Integer, Integer> getMap() {
return map;
} public void setMap(Map<Integer, Integer> map) {
this.map = map;
} public String toString(){
String str = "name:"+name+" age:"+age+" single:"+single+" ";
if(null != map && map.size() > 0){
str += "map[";
Iterator<Integer> it = map.keySet().iterator();
while(it.hasNext()){
Integer key = it.next();
Integer value = map.get(key);
str += key+":"+value+" ";
}
str += "]";
}
return str;
}
}
package com.sean;

import java.util.HashMap;
import java.util.Map; import org.apache.commons.beanutils.BeanUtils; public class Test {
public static void main(String[] args) throws Exception {
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
map.put(1, 1);
User u1 = new User("tom",123,true,map);
User u2 = new User();
BeanUtils.copyProperties(u2, u1);
System.out.println(u1.toString());
System.out.println(u2.toString());
}
}

运行结果为(比较复杂的属性也可以被复制并且只有拥有get/set方法的属性才可以被复制):

name:tom age:123 single:true map[1:1 ]
name:tom age:null single:true map[1:1 ]

更详细的使用说明就不介绍了,接下来看看BeanUtils是如何实现的,好戏刚刚开始

BeanUtils:

.......
public static void copyProperties(Object dest, Object orig)
throws IllegalAccessException, InvocationTargetException {
BeanUtilsBean.getInstance().copyProperties(dest, orig);
}
......
/**
* Gets the instance which provides the functionality for {@link BeanUtils}.
* This is a pseudo-singleton - an single instance is provided per (thread) context classloader.
* This mechanism provides isolation for web apps deployed in the same container.
*
* @return The (pseudo-singleton) BeanUtils bean instance
*/
public static BeanUtilsBean getInstance() {
return BEANS_BY_CLASSLOADER.get();
}
......

这里特意带上了方法说明,getInstance()方法并不是一个简单的单例模式,而是一个“伪单例”模式

ContextClassLoaderLocal<T>:

......
private static final ContextClassLoaderLocal<BeanUtilsBean> BEANS_BY_CLASSLOADER
= new ContextClassLoaderLocal<BeanUtilsBean>() {
// Creates the default instance used when the context classloader is unavailable
@Override
protected BeanUtilsBean initialValue() {
return new BeanUtilsBean();
}
};
......
/**
* Gets the instance which provides the functionality for {@link BeanUtils}.
* This is a pseudo-singleton - an single instance is provided per (thread) context classloader.
* This mechanism provides isolation for web apps deployed in the same container.
* @return the object currently associated with the context-classloader of the current thread.
*/
public synchronized T get() {
// synchronizing the whole method is a bit slower
// but guarantees no subtle threading problems, and there's no
// need to synchronize valueByClassLoader // make sure that the map is given a change to purge itself
valueByClassLoader.isEmpty();
try {
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
if (contextClassLoader != null) { T value = valueByClassLoader.get(contextClassLoader);
if ((value == null) && !valueByClassLoader.containsKey(contextClassLoader)) {
value = initialValue();
valueByClassLoader.put(contextClassLoader, value);
}
return value;
}
} catch (SecurityException e) { /* SWALLOW - should we log this? */ }
// if none or exception, return the globalValue
if (!globalValueInitialized) {
globalValue = initialValue();
globalValueInitialized = true;
}//else already set
return globalValue;
}
.......

和ContextClassLoader配合实现了一个线程中单例的“伪单例”模式,真正的亮点

Apache Commons Beanutils对象属性批量复制(pseudo-singleton)的更多相关文章

  1. Apache Commons Beanutils 一 (使用PropertyUtils访问Bean属性)

    BeanUtils简要描述 beanutils,顾名思义,是java bean的一个工具类,可以帮助我们方便的读取(get)和设置(set)bean属性值.动态定义和访问bean属性: 细心的话,会发 ...

  2. BeanUtils对象属性copy的性能对比以及源码分析

    1. 对象属性拷贝的常见方式及其性能 在日常编码中,经常会遇到DO.DTO对象之间的转换,如果对象本身的属性比较少的时候,那么我们采用硬编码手工setter也还ok,但如果对象的属性比较多的情况下,手 ...

  3. org.springframework.beans.BeanUtils与org.apache.commons.beanutils.BeanUtils的copyProperties用法区别

    知识点 org.springframework.beans.BeanUtils与org.apache.commons.beanutils.BeanUtils都提供了copyProperties方法,作 ...

  4. org.apache.commons.beanutils.BeanUtils的常见用法

    import org.apache.commons.beanutils.BeanUtils BeanUtils1. public static void copyProperty(Object bea ...

  5. Apache Commons Beanutils 三 (BeanUtils、ConvertUtils、CollectionUtils...)

    前言 前面已经学习了Apache Commons Beanutils包里的PropertyUtils和动态bean,接下来将学习剩下的几个工具类,个人觉得还是非常实用的,特别是CollectionUt ...

  6. Apache Commons Beanutils 二 (动态Bean - DynaBeans)

    相关背景 上一篇介绍了PropertyUtils的用法,PropertyUtils主要是在不修改bean结构的前提下,动态访问bean的属性: 但是有时候,我们会经常希望能够在不定义一个Java类的前 ...

  7. org.apache.commons.beanutils.ConversionException: No value specified解决办法

    转自:https://www.cnblogs.com/linjiqin/archive/2011/07/21/2112628.html 当用到了java.sql.Date时间等非内置对象时,如果对象为 ...

  8. org.apache.commons.beanutils.BeanMap简单使用例子

    一.org.apache.commons.beanutils.BeanMap; 将一个java bean允许通过map的api进行调用, 几个支持的操作接口: Object get(Object ke ...

  9. 再续前缘-apache.commons.beanutils的补充

    title: 再续前缘-apache.commons.beanutils的补充 toc: true date: 2016-05-32 02:29:32 categories: 实在技巧 tags: 插 ...

随机推荐

  1. MySQL 线上配置文件

    [client] port            = 3306 socket          = /tmp/mysql.sock default-character-set = utf8 [mysq ...

  2. HDU4526威威猫系列故事——拼车记(DP)

    http://acm.hdu.edu.cn/showproblem.php?pid=4526 额..七夕快乐哦 刚推的时候有点乱 又各种小错误 查了好久.. dp[i][k] = min(dp[i-1 ...

  3. Atom 扩展离线安装

    1.下载原始包 2.解压放入atom的packages文件夹中 3.通过nodejs的npm指令进行安装 运行->cmd 4.重启Atom就ok了

  4. HDU-1240 Asteroids! (BFS)这里是一个三维空间,用一个6*3二维数组储存6个不同方向

    Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Submission ...

  5. spatialite-android-library 环境搭建

    spatialite-android-library项目介绍 搭建NDK开发环境 下载spatialite-android-library项目 搭建spatialite-android-library ...

  6. 【原】本地win7,远程服务器XP系统,两台机器间不能拖动文件

    (1)网上大部分说是rdpclip.exe(存放在c:/windows/system32)的问题,试了好几次,没有解决 (2)通过第二种方式解决,详细步骤如下所示: 1.点击进入远程连接. 2.选择本 ...

  7. Java笔记(二十九)……网络编程

    概述 网络模型 网络通讯的要素 ip地址:网络中设备的标识符 端口:用于标识同一台设备上不同的进程,有效端口:0~65535,其中0~1024是系统使用端口或者保留端口 TCP与UDP UDP特点: ...

  8. 初探WebService

    写博客也是一件非常费时的事儿啊,之前配置服务器和客户端的Oracle数据库搞了很久,搞定之后懒的记录,现在想想如果让我再配一次,估计又要花很长时间了. 所以把做过的东西整理整理记录下来还是很有必要的, ...

  9. HW4.9

    import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner i ...

  10. poj 2367 Genealogical tree (拓扑排序)

    火星人的血缘关系很奇怪,一个人可以有很多父亲,当然一个人也可以有很多孩子.有些时候分不清辈分会产生一些尴尬.所以写个程序来让n个人排序,长辈排在晚辈前面. 输入:N 代表n个人 1~n 接下来n行 第 ...