Cglib是一款比較底層的操作java字節碼的框架。
BeanCopier是一個工具類,可以用於Bean對象內容的復制。
復制Bean對象內容的方法有很多,比如自己手動get set ,或者使用PropertyUtils或者使用BeanUtils
BeanCopier與 PropertyUtils 、BeanUtils的不同在於:
PropertyUtils 和 BeanUtils 使用的是反射機制來完成屬性的復制。
而BeanCopier 的原理是通過字節碼動態生成一個類,這個里面實現get 和 set方法。(性能和對象直接調用set一樣)
BeanCopier 唯一的花銷是生成動態類上,但是生成的后的象可以自己保存起來反復使用。
根據網上的資料 BeanCopier的性能是PropertyUtils (apache-common)的500倍。 PropertyUtils的性能是BeanUtils(apache-common)的2倍。
以下是使用例子
import net.sf.cglib.beans.BeanCopier; public class BeanCopierTest { public static void main(String[] args) { Bean1 bean1 = new Bean1(); Bean2 bean2 = new Bean2(); bean1.setValue("hello"); BeanCopier copier = BeanCopier.create(Bean1.class, Bean2.class, false); copier.copy(bean1, bean2, null); System.out.println(bean2.getValue()); } static class Bean1 { private String value; public String getValue() { return value; } public void setValue(String value) { this.value = value; } } static class Bean2 { private String value; public String getValue() { return value; } public void setValue(String value) { this.value = value; } } }
注意事項:BeanCopier在復制的時候使用get和set方法了。如果方法定義不嚴格,會造成復制的對象屬性值不正確。