最近在使用Apache的BeanUtils的时候,看了一下源代码。对静态方法copyProperties的一些分析
当我们调用BeanUtils.copyProperties(dest,orig)方法的时候.
1.程序会根据环境上下文创建一个BeanUtilsBean对象,再根据该对象调用其方法copyProperties(dest,orig),源代码如下.
BeanUtilsBean.getInstance().copyProperties(dest, orig);
public static BeanUtilsBean getInstance() {
return (BeanUtilsBean) BEANS_BY_CLASSLOADER.get();
}
/**
* Contains <code>BeanUtilsBean</code> instances indexed by context classloader.
*/
private static final ContextClassLoaderLocal
BEANS_BY_CLASSLOADER = new ContextClassLoaderLocal() {
// Creates the default instance used when the context classloader is unavailable
protected Object initialValue() {
return new BeanUtilsBean();
}
};
2.创建BeanUtilsBean对象的时候,会创建用于设置属性值的new ConvertUtilsBean()对象,和用于访问属性new PropertyUtilsBean()对象,代码如下.当在BeanUtilsBean对象中注册好了这两个对象后,才会开始使用copyProperties方法.
public BeanUtilsBean() {
this(new ConvertUtilsBean(), new PropertyUtilsBean());
}
3.注意,在正式使用我们的copyProperties方法的时候,我们的程序会先在new ConvertUtilsBean()对象的时候做一些事情,什么事情呢?就是注册转换器.我们可以看到ConvertUtilsBean的构造方法如下,它是在做什么捏?我们看人家老外的注释就知道,这是在创建一个拥有一个标准的转换器,并且将它注册.那个setFast是做什么的?这个是个模式(非设计模式,自己去看源代码的注释哈,暂时忽略)
/** Construct a bean with standard converters registered */
public ConvertUtilsBean() {
converters.setFast(false);
deregister();
converters.setFast(true);
}
4.这个标准是什么,注册的时候发生了什么事情?注册很多标准的转换器.以下我只写出了 registerPrimitives(false);的方法中的转换器注册哈.另外的大多都是时间,URL,数组等等其他的标准转换器.如何标准法?就要去看每一个转换器里面是怎么个标准了哈.不过8个基本类型是有的,其中说明转换出异常的话,char是会变成" "而String是""哈.
public void deregister() {
converters.clear();
registerPrimitives(false);
registerStandard(false, false);
registerOther(true);
registerArrays(false, 0);
register(BigDecimal.class, n