Java tutorial
//package com.java2s; //License from project: Apache License import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Main { /** * Copy fields from parent object to new child object. * * @param parent parent object * @param childClass child class * @param <T> child class * @return filled child object */ public static <T> T shallowCopy(Object parent, Class<T> childClass) { try { return shallowCopy(parent, childClass.newInstance()); } catch (Exception e) { throw new RuntimeException(e); } } /** * Copy fields from parent object to child object. * * @param parent parent object * @param child child object * @param <T> child class * @return filled child object */ public static <T> T shallowCopy(Object parent, T child) { try { List<Field> fields = new ArrayList<>(); Class clazz = parent.getClass(); do { fields.addAll(Arrays.asList(clazz.getDeclaredFields())); } while (!(clazz = clazz.getSuperclass()).equals(Object.class)); for (Field field : fields) { field.setAccessible(true); field.set(child, field.get(parent)); } return child; } catch (Exception e) { throw new RuntimeException(e); } } }