Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 707
Alex Avatar asked Oct 30 '25 03:10

Alex


1 Answers

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;
}
like image 65
Manikandan Avatar answered Nov 01 '25 17:11

Manikandan