Copy POJO content from one bean to another

后端 未结 7 1215
臣服心动
臣服心动 2020-11-30 13:50

I have few Pojos in different packages, each POJO contains set of the another pojo from the same package. I need to copy all items with the same name from Package B Pojos to

相关标签:
7条回答
  • 2020-11-30 14:17

    Using PropertyUtils, you can copy onky the non null properties as follows:

        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());
            }
    
        }
    
    0 讨论(0)
  • 2020-11-30 14:22

    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.

    0 讨论(0)
  • 2020-11-30 14:23

    Copying fields values are a need I almost every project, for example for do the clone(). I also think that for accomplish some goals isn't necessary import .jars for using only one function. 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.

    0 讨论(0)
  • 2020-11-30 14:30

    If you already have spring dependencies you could use org.springframework.beans.BeanUtils

    BeanUtils.copyProperties(from, to);
    
    0 讨论(0)
  • 2020-11-30 14:32

    Any reason why Apache BeanUtils.copyProperties does not work?

    0 讨论(0)
  • 2020-11-30 14:32

    If DRY is a bedrock principle of computer science, what reason can you give for two identical, parallel object graphs? 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.

    0 讨论(0)
提交回复
热议问题