为了将部分属性从Java对象复制到另一个对象,可以使用实用程序类和反射复制指定字段的方法。以下是一个例子:
public class ObjectCopier { public static void copyFields(Object source, Object destination, String... fields) throws IllegalAccessException { Class<?> sourceClass = source.getClass(); Class<?> destinationClass = destination.getClass(); for (String field : fields) { Field sourceField = null; try { sourceField = sourceClass.getDeclaredField(field); } catch (NoSuchFieldException e) { // Ignore fields that don't exist in the source object continue; } Field destinationField = null; try { destinationField = destinationClass.getDeclaredField(field); } catch (NoSuchFieldException e) { // Ignore fields that don't exist in the destination object continue; } sourceField.setAccessible(true); destinationField.setAccessible(true); destinationField.set(destination, sourceField.get(source)); } }}
测试
@Datapublic class User { private String warehouseCode; private String warehouseName; private Integer deductType; private String deductOrderCode; private BigDecimal deductAmount;}@Datapublic class User2 { private String warehouseCode; private String warehouseName; private Integer deductType; public static void main(String[] args) throws IllegalAccessException { User2 user2 = new User2(); user2.setWarehouseCode("code"); user2.setWarehouseName("name"); user2.setDeductType(111); User user = new User(); ObjectCopier.copyFields(user2,user,"warehouseCode","warehouseName"); System.out.println(user); }}
测试结果
