Search This Blog

Wednesday, July 19, 2017

How to copy properties from one Java bean to another?

We can copy properties from one Java bean to another using Java Reflection API.

public static <T> void copy(T target, T source) throws Exception {
    Class<?> clazz = source.getClass();

    for (Field field : clazz.getDeclaredFields()) {
        if (Modifier.isPrivate(field.getModifiers()))
            field.setAccessible(true);
        Object value = field.get(source);
        field.set(target, value);
    }
}

No comments:

Post a Comment