I want to create copy of object via
Reflection API
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;
}
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;
}