BeanUtils和PropertyUtils類是許多開(kāi)源框架中頻繁使用的兩個(gè)工具,它們都能實(shí)現(xiàn)將一個(gè)類中的屬性拷貝到另一個(gè)類中,這個(gè)功能甚至是spring實(shí)現(xiàn)依賴注入的基礎(chǔ)。研究一下apache的comon包中如何實(shí)現(xiàn)這個(gè)兩個(gè)工具,可以發(fā)現(xiàn)它們都是使用java.lang.reflect和java.beans這兩個(gè)包下的幾個(gè)類來(lái)實(shí)現(xiàn)的。
這里我們通過(guò)編寫一個(gè)將一個(gè)類的所有屬性拷貝到另一個(gè)類的相應(yīng)屬性的方法來(lái)分析是如何實(shí)現(xiàn)拷貝功能的.先把方法放上來(lái):

/** *//** 實(shí)現(xiàn)將源類屬性拷貝到目標(biāo)類中
* @param source
* @param target
*/

public static void copyProperties(Object source, Object target)
{

try
{
//獲取目標(biāo)類的屬性信息
BeanInfo targetbean = Introspector.getBeanInfo(target.getClass());
PropertyDescriptor[] propertyDescriptors = targetbean.getPropertyDescriptors();
//對(duì)每個(gè)目標(biāo)類的屬性查找set方法,并進(jìn)行處理

for (int i = 0; i < propertyDescriptors.length; i++)
{
PropertyDescriptor pro = propertyDescriptors[i];
Method wm = pro.getWriteMethod();

if (wm != null)
{//當(dāng)目標(biāo)類的屬性具有set方法時(shí),查找源類中是否有相同屬性的get方法
BeanInfo sourceBean = Introspector.getBeanInfo(source.getClass());
PropertyDescriptor[] sourcepds = sourceBean.getPropertyDescriptors();

for (int j = 0; j < sourcepds.length; j++)
{

if (sourcepds[j].getName().equals(pro.getName()))
{ //匹配
Method rm = sourcepds[j].getReadMethod();
//如果方法不可訪問(wèn)(get方法是私有的或不可達(dá)),則拋出SecurityException

if (!Modifier.isPublic(rm.getDeclaringClass().getModifiers()))
{
rm.setAccessible(true);
}
//獲取對(duì)應(yīng)屬性get所得到的值
Object value = rm.invoke(source,new Object[0]);

if (!Modifier.isPublic(wm.getDeclaringClass().getModifiers()))
{
wm.setAccessible(true);
}
//調(diào)用目標(biāo)類對(duì)應(yīng)屬性的set方法對(duì)該屬性進(jìn)行填充

wm.invoke((Object) target, new Object[]
{ value });
break;
}
}
}
}

} catch (IntrospectionException e)
{
e.printStackTrace();

} catch (IllegalArgumentException e)
{
e.printStackTrace();

} catch (IllegalAccessException e)
{
e.printStackTrace();

} catch (InvocationTargetException e)
{
e.printStackTrace();
}
}

兩個(gè)工具的其他方法實(shí)現(xiàn)雖然有點(diǎn)差別,但原理都跟上面的例子差不多,有興趣的話可以寫個(gè)測(cè)試類試試是否可以使用.
轉(zhuǎn)自: http://lemonfamily.blogdriver.com/lemonfamily/1240784.html