Alex Alex - 3 years ago 124
Java Question

How can I make a copy of object via Reflection API?

I want to create copy of object via

Reflection API
. Here is my code:

private <T> T copy(T entity) throws IllegalAccessException, InstantiationException {
List<Field> fields = new ArrayList<Field>();
Field[] retrievedFields = entity.getClass().getDeclaredFields();
for (Field field : retrievedFields) {
fields.add(field);
}
T newEntity = (T) entity.getClass().newInstance();
for (Field field : fields) {
field.setAccessible(true);
field.set(newEntity, field.get(entity));
}
return newEntity;
}


But I don't know how to get values of fields.

Answer Source

You can use superClass to get superClass. "Object" will be superClass of all class. SuperClass of Object is null. Either you can check for "Object" or null for terminating condition. Anyhow declaredFields for Object wont return anything.

private <T> T copy(T entity) throws IllegalAccessException, InstantiationException {
    Class<?> clazz = entity.getClass();
    T newEntity = (T) entity.getClass().newInstance();

    while (clazz != null) {
        copyFields(entity, newEntity, clazz);
        clazz = clazz.getSuperclass();
    }

    return newEntity;
}

private <T> T copyFields(T entity, T newEntity, Class<?> clazz) throws IllegalAccessException {
    List<Field> fields = new ArrayList<>();
    for (Field field : clazz.getDeclaredFields()) {
        fields.add(field);
    }
    for (Field field : fields) {
        field.setAccessible(true);
        field.set(newEntity, field.get(entity));
    }
    return newEntity;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download