Copying one class's fields into another class's identical fields

后端 未结 4 1253
耶瑟儿~
耶瑟儿~ 2021-01-02 04:23

I have this question. But it will be difficult for me to explain as I don\'t know exact terms to use. Hope someone will understand. I\'ll try to discribe to the best i can.

4条回答
  •  -上瘾入骨i
    2021-01-02 05:00

    Dozer is fine, see Jean-Remy's answer.

    Also, if the variables have getters and setters according to the JavaBeans standard, there are a number of technologies that could help you, e.g. Apache Commons / BeanUtils

    Sample code (not tested):

    final Map aProps = BeanUtils.describe(a);
    final Map bProps = BeanUtils.describe(b);
    aProps.keySet().retainAll(bProps.keySet());
    for (Entry entry : aProps.entrySet()) {
        BeanUtils.setProperty(b,entry.getKey(), entry.getValue());
    }
    

    Update:

    If you don't have getters and setters, here's a quick hack that copies field values from one class to another as long as the fields have common names and types. I haven't tested it, but it should be OK as a starting point:

    public final class Copier {
    
        public static void copy(final Object from, final Object to) {
            Map fromFields = analyze(from);
            Map toFields = analyze(to);
            fromFields.keySet().retainAll(toFields.keySet());
            for (Entry fromFieldEntry : fromFields.entrySet()) {
                final String name = fromFieldEntry.getKey();
                final Field sourceField = fromFieldEntry.getValue();
                final Field targetField = toFields.get(name);
                if (targetField.getType().isAssignableFrom(sourceField.getType())) {
                    sourceField.setAccessible(true);
                    if (Modifier.isFinal(targetField.getModifiers())) continue;
                    targetField.setAccessible(true);
                    try {
                        targetField.set(to, sourceField.get(from));
                    } catch (IllegalAccessException e) {
                        throw new IllegalStateException("Can't access field!");
                    }
                }
            }
        }
    
        private static Map analyze(Object object) {
            if (object == null) throw new NullPointerException();
    
            Map map = new TreeMap();
    
            Class current = object.getClass();
            while (current != Object.class) {
                for (Field field : current.getDeclaredFields()) {
                    if (!Modifier.isStatic(field.getModifiers())) {
                        if (!map.containsKey(field.getName())) {
                            map.put(field.getName(), field);
                        }
                    }
                }
                current = current.getSuperclass();
            }
            return map;
        }
    }
    

    Call Syntax:

    Copier.copy(sourceObject, targetObject);
    

提交回复
热议问题