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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With