简体   繁体   English

将 POJO 内容从一个 bean 复制到另一个 bean

[英]Copy POJO content from one bean to another

I have few Pojos in different packages, each POJO contains set of the another pojo from the same package.我在不同的包中很少有 Pojo,每个 POJO 都包含来自同一包的另一个 pojo 的集合。 I need to copy all items with the same name from Package B Pojos to objects in Package A.我需要将包 B Pojos 中的所有同名项目复制到包 A 中的对象。

Eaxmple:例如:

package com.vanilla.packageA;

public class Student{

    private String firstName;
    private String lastName;
    private Set<Course> course;

    //getters and setters ommited

}   

package com.vanilla.packageA;

    public class Course{
    private String courseName;
    private String courseDescription;

    //seters and getters
}

package com.vanilla.packageB;

public class Student{

    private String firstName;
    private String lastName;
    private Address address;
    private Set<Course> course;
    Private Date birtday;

    //getters and setters ommited

}   

package com.vanilla.packageB;

public class Course{
    private String courseName;
    private String courseDescription;
    private <Lecturer> lecturer;
    private Integer hours;

    //seters and getters
} 

I want to copy recursively all items from PackageB classes to packageA classes which exists in PaCkageB and shares the same name.我想递归地将PackageB类中的所有项目复制到存在于PaCkageB并共享相同名称的packageA类。

Updates:更新:

Guys, I understand that that this is stupid question, but I need to maintain this code, now the code is written in the way that they have to call 50 getters and setter, or calling constructor with 50 parameters.伙计们,我知道这是一个愚蠢的问题,但我需要维护这段代码,现在代码的编写方式是他们必须调用 50 个 getter 和 setter,或者调用带有 50 个参数的构造函数。 Unfortunately, I can't use the same object and I need to copy it, but I must find more "elegant" way to copy tese beans.不幸的是,我不能使用同一个对象,我需要复制它,但我必须找到更“优雅”的方式来复制 tese beans。

Apache BeanUtils.copyProperties不起作用的任何原因?

Well.. Dozer may be just the thing you're looking for.嗯..推土机可能正是您正在寻找的东西。

. . . . . . its an object to object mapping framework.它是一个对象到对象映射框架。 The idea is that:这个想法是:

  • Usually it will map by convention.通常它会按惯例映射。
  • You can override this convention with a mapping file.您可以使用映射文件覆盖此约定。

. . . . therefore mapping files are as compact as possible.因此映射文件尽可能紧凑。 Its useful for many cases, such as mapping a use-case specify service payload on to the reusable core model objects.它在许多情况下很有用,例如将用例指定的服务有效负载映射到可重用的核心模型对象上。

When delivering the SpringSource training courses we used to point out this framework very often.在提供 SpringSource 培训课程时,我们曾经经常指出这个框架。

See to mapstruct .请参阅mapstruct This tools generates code, so there is no overhead on reflection.该工具生成代码,因此没有反射开销。

如果您已经有 spring 依赖项,则可以使用org.springframework.beans.BeanUtils

BeanUtils.copyProperties(from, to);

Copying fields values are a need I almost every project, for example for do the clone().几乎每个项目都需要复制字段值,例如执行 clone()。 I also think that for accomplish some goals isn't necessary import .jars for using only one function.我还认为,为了实现某些目标,不必为了仅使用一个功能而导入 .jars。 I would like share some little code in which I was working, there are some things that I left in the inkwell but in general it do the work.我想分享一些我正在使用的小代码,有些东西我留在墨水瓶中,但总的来说它可以完成工作。 In this case I use reflection.在这种情况下,我使用反射。

public class ObjectCopyTools {

static String[] bases = new String[] {"byte", "short", "int", "long", "float", "double", "char", "boolean"};
static String[] equivalents = new String[] {"Byte", "Short", "Integer", "Long", "Float", "Double", "Character", "Boolean"};

static {

}

private static boolean areEquivalents(String type1, String type2){
    for (int i = 0; i < bases.length; i++) {
        if((type1.equals(bases[i]) && type2.equals(equivalents[i])) 
                || (type2.equals(bases[i]) && type1.equals(equivalents[i]))){
            return true;
        }
    }
    return false;
}

public static <T extends Object, Y extends Object> Y deepReflectionObjectCopy(T origin, Class<Y> resultClass) {
    Class<? extends Object> origClass = origin.getClass();
    Y resultObject = null;
    for (Constructor<?> constructor : resultClass.getConstructors()) {
        if (constructor.getParameterCount() == 0) {
            try {
                resultObject = (Y) constructor.newInstance();
            }catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            }
            break;
        }
    }
    if(resultObject == null){
        return null;
    }
    Field[] origFields = origClass.getDeclaredFields();
    Field[] destFields = resultObject.getClass().getDeclaredFields();

    Object value = null;
    for(Field dstField: destFields){
        try {
            Field tempOrigField = origClass.getDeclaredField(dstField.getName());
            if(tempOrigField.getType().equals(dstField.getType())
                    || areEquivalents(tempOrigField.getType().getSimpleName(), dstField.getType().getSimpleName())){
                dstField.set(resultObject, tempOrigField.get(origin));
            }
        } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
        }
    }
    return resultObject;
}

Hope this help.希望这有帮助。

Using PropertyUtils, you can copy onky the non null properties as follows:使用 PropertyUtils,您可以复制 onky 非空属性,如下所示:

    private void copyNonNullProperties(Object destination,
            Object source) {
        try {
            PropertyUtils.describe(source).entrySet().stream()
                    .filter(source -> source.getValue() != null)
                    .filter(source -> !source.getKey().equals("class"))
                    .forEach(source -> {
                        try {
                            PropertyUtils.setProperty(destination, source.getKey(), source.getValue());
                        } catch (Exception e22) {
                            log.error("Error setting properties : {}", e22.getMessage());
                        }
                    });

        } catch (Exception e1) {
            log.error("Error setting properties : {}", e1.getMessage());
        }

    }

If DRY is a bedrock principle of computer science, what reason can you give for two identical, parallel object graphs?如果 DRY 是计算机科学的基本原理,那么您可以为两个相同的平行对象图给出什么理由? Not only have you doubled your maintenance burden, but now you have to develop a recursive method to do nothing but ferry data from one to the other.您不仅使维护负担增加了一倍,而且现在您必须开发一种递归方法,除了将数据从一个传输到另一个之外什么都不做。

have you tried using BULL ?你试过使用BULL吗? you can find a guide on how to use it on DZone .您可以在DZone上找到有关如何使用它的指南。 It offers the possibility to also perform object transformation while coping.它提供了在应对时也执行对象转换的可能性。 Moreover, it performs the copy recursively and don't need getter and setters defined.此外,它递归地执行复制,不需要定义 getter 和 setter。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM