首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Java对象指定部分/全部属性copy工具类

Java对象指定部分/全部属性copy工具类

原创
作者头像
疯狂的KK
修改2023-04-06 17:16:21
修改2023-04-06 17:16:21
1.2K00
代码可运行
举报
文章被收录于专栏:Java项目实战Java项目实战
运行总次数:0
代码可运行

要将部分属性从一个Java对象复制到另一个对象,可以使用一个实用程序类和一个利用反射复制指定字段的方法。以下是一个示例实现:

代码语言:javascript
代码运行次数:0
运行
复制
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));
        }
    }
}

测试

代码语言:javascript
代码运行次数:0
运行
复制
@Data
public class User {

    private String warehouseCode;


    private String warehouseName;


    private Integer  deductType;


    private String  deductOrderCode;


    private BigDecimal deductAmount;
}


@Data
public 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);
    }
}

测试结果

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档