-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReflectionCopier.java
More file actions
33 lines (27 loc) · 931 Bytes
/
ReflectionCopier.java
File metadata and controls
33 lines (27 loc) · 931 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package practice.reflection;
import java.lang.reflect.Field;
public class ReflectionCopier {
public static void copyFields(Object source, Object target) {
if (source == null || target == null) {
throw new IllegalArgumentException("Source and target must not be null!");
}
Class<?> clazz = source.getClass();
if (!clazz.equals(target.getClass())) {
throw new IllegalArgumentException("Source and target must be from the same class!");
}
while (clazz != null) {
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true); // Access to private fields
try {
Object value = field.get(source);
field.set(target, value);
} catch (IllegalAccessException e) {
System.err.println("Failed to copy field: " + field.getName());
e.printStackTrace();
}
}
clazz = clazz.getSuperclass();
}
}
}