I have the following.
public static <T> T someMethod(T originalObject) {
T modifiedObject = /* copy of original object (HOW DO YOU DO THIS?) */
/* Some logic that modifies the object. */
...
return modifiedObject; // without changing original Object
}
The question is then, how to a create a copy of type T if you have no idea what type T could be?
REVISION - to be more clear I will just paste my code.
public class ObjectMerger {
public static <T> T merge(T original, T patch) throws IllegalArgumentException, IllegalAccessException {
Object mergedObject = original // TODO: implement a way to copy original
Field[] inheritedFields = patch.getClass().getFields();
Field[] memberFields = patch.getClass().getDeclaredFields();
Field[] allFields = (Field[]) ArrayUtils.addAll(inheritedFields, memberFields);
for (Field field : allFields) {
Boolean originalAccessibility = field.isAccessible();
field.setAccessible(true);
Object fieldValue = field.get(patch);
if (fieldValue != null) {
Boolean fieldIsFinal = Modifier.isFinal(field.getModifiers());
if (!fieldIsFinal) {
field.set(mergedObject, fieldValue);
}
}
field.setAccessible(originalAccessibility);
}
return mergedObject;
}
}
Note: I have tried saying T extends Cloneable and it's a no go. I believe that implementing Cloneable does not ensure clone is visible.
NOTE: NOTE A DUPLICATE!
For those marking this as a duplicate please read the question. This is asking for a way to duplicate an object of a unknown type. Anyways from what I have come to understand this is not possible. Thanks to everyone for your input.