I tried following code copyCustom() to copy an object and create a new object with original object content. Once I got new object copy. I modified some content (String content) using get/set methods, unforturnately the contents of original object also changed. In other words, new object copy referring to original object. I just need an object with deep copying without any references to original object
@SuppressWarnings("unchecked")
private <T> T copyCustom(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<Field>();
for (Field field : clazz.getDeclaredFields()) {
fields.add(field);
}
for (Field field : fields) {
field.setAccessible(true);
// next we change the modifier in the Field instance to
// not be final anymore, thus tricking reflection into
// letting us modify the static final field
Field modifiersField;
try {
modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
int modifiers = modifiersField.getInt(field);
// blank out the final bit in the modifiers int
modifiers &= ~Modifier.FINAL;
modifiersField.setInt(field, modifiers);
field.set(newEntity, field.get(entity));
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return newEntity;
}