對於兩個實體類屬性值的合並,java實現。
對於實現,主要是使用 java 的反射機制。
首先需要構造一個實體類(TestModel.java):
package test; public class TestModel { private String prop1; private String prop2; private String prop3; public String getProp1() { return prop1; } public void setProp1(String prop1) { this.prop1 = prop1; } public String getProp2() { return prop2; } public void setProp2(String prop2) { this.prop2 = prop2; } public String getProp3() { return prop3; } public void setProp3(String prop3) { this.prop3 = prop3; } //用於輸出字符串 @Override public String toString() { return "prop1:"+prop1+"\nprop2:"+prop2+"\nprop3:"+prop3; } }
然后緊接着創建一個合並相同實體的功能類():
package test; import java.lang.reflect.Field; public class CombineBeans { /** * 該方法是用於相同對象不同屬性值的合並,如果兩個相同對象中同一屬性都有值,那么sourceBean中的值會覆蓋tagetBean重點的值 * @param sourceBean 被提取的對象bean * @param targetBean 用於合並的對象bean * @return targetBean,合並后的對象 */ private TestModel combineSydwCore(TestModel sourceBean,TestModel targetBean){ Class sourceBeanClass = sourceBean.getClass(); Class targetBeanClass = targetBean.getClass(); Field[] sourceFields = sourceBeanClass.getDeclaredFields(); Field[] targetFields = targetBeanClass.getDeclaredFields(); for(int i=0; i<sourceFields.length; i++){ Field sourceField = sourceFields[i];
if(Modifier.isStatic(sourceField.getModifiers())){
continue;
} Field targetField = targetFields[i];
if(Modifier.isStatic(targetField.getModifiers())){
continue;
} sourceField.setAccessible(true); targetField.setAccessible(true); try { if( !(sourceField.get(sourceBean) == null) && !"serialVersionUID".equals(sourceField.getName().toString())){ targetField.set(targetBean,sourceField.get(sourceBean)); } } catch (IllegalArgumentException | IllegalAccessException e) { e.printStackTrace(); } } return targetBean; } //測試 combineBeans方法 public static void main(String[] args) { TestModel sourceModel = new TestModel(); // 第一個對象 TestModel targetModel = new TestModel(); // 第二個model對象 sourceModel.setProp1("1"); sourceModel.setProp2("1"); targetModel.setProp2("2"); targetModel.setProp3("2"); CombineBeans test = new CombineBeans(); test.combineSydwCore(sourceModel, targetModel); System.out.println(targetModel.toString()); } }
輸出的結果如下:
根據控制台中打印結果發現:
原來的targetModel屬性值:
prop1:null prop2:2 prop3:2
合並之后的targetModel屬性值:
prop1:1 prop2:1 prop3:2
targetModel中的 prop1 屬性被 sourceModel 中的 prop1 屬性填充;prop2 屬性被 prop1 覆蓋。
到此,over !!! ^_^
-----------------------------
在后續使用中發現,應該排除 靜態域,具體判斷方法參考:https://blog.csdn.net/zhou8622/article/details/44038699