[英]How to copy a subset of properties from Bean A to Bean B in Java?
本質上,我正在尋找一種簡單的方法,例如:
BeanUtils.copyProperties(dest, orig);
這來自apache,但是將所有屬性從起點復制到目的地。 我需要只復制某些屬性子集的東西...類似下面的東西
String[] propertyNamesToCopy = {"firstName", "lastName"};
BeanUtils.copyProperties(dest, orig, propertyNamesToCopy);
有什么建議么?
您可以使用BeanUtils的copyProperty
復制單個屬性。 只需循環使用屬性即可。 您可以將其提取為方法。
您可以通過反射來實現。
public void copyProperties(Object orig, Object dest, String[] props){
Class<?> class = orig.getClass().getFields();
for(String fieldName : props){
Field field = class.getField( fieldName );
field.set(dest, field.get(orig));
}
}
我沒有嘗試過,這種方法可能會導致一些問題。
首先,您需要添加try / catch,以防該字段不存在。 然后,它僅適用於public
領域。 另外,表單Field
的get()
方法僅返回對象,我不知道它是否會自動裝箱/拆箱,這可能會生成運行時錯誤並迫使您使用getInt()
等,具體取決於FieldType
(可以通過field.getGenericType()
獲得它。 您可能會看到getDeclaredField()
,它獲取所有字段(甚至私有),但僅針對您擁有的類,而不是從父項繼承的字段。
如果要訪問私有字段,請使用反射將它們設置為公共field.setaccessible(true)
如果我正確的話,請使用field.setaccessible(true)
),也可以通過它們的getter和setter訪問它們(也可以使用反射):
Method get = class.getMethod("get"+fieldNameWithCaps);
Object newValue = get.invoke(orig)
Method set = class.getMethod("set"+fieldNameWithCaps, newValue.getClass());
set.invoke(dest, newValue);
仍然不確定此處,因為我不知道newValue.getClass()
將返回什么,但是您明白了。 嘗試環顧四周的反射,但要小心,它的速度很慢,可能會很雜亂。
Spring的BeanUtils類實質上提供了我所尋找的逆。 因此,我獲取所有屬性的列表-要復制的屬性列表以獲取忽略列表,但它可以正常工作:-)
org.springframework.beans.BeanUtils.copyProperties(Object source, Object target, String... ignoreProperties)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.