728x90
- Reflection 활용하여 객체 필드 복사하기
public class ReflectionExample {
public static void copyFields(Object source, Object target) throws Exception {
Class<?> sourceClass = source.getClass();
Class<?> targetClass = target.getClass();
Field[] sourceFields = sourceClass.getDeclaredFields();
for (Field sourceField : sourceFields) {
try {
Field targetField = targetClass.getDeclaredField(sourceField.getName());
sourceField.setAccessible(true);
targetField.setAccessible(true);
Object value = sourceField.get(source); // 원본 객체의 값을 읽음
targetField.set(target, value); // 대상 객체에 값을 설정
} catch (NoSuchFieldException e) {
// target 클래스에 해당 필드가 없으면 무시
}
}
}
public static void main(String[] args) throws Exception {
class Source {
private String name = "John";
private int age = 30;
}
class Target {
private String name;
private int age;
}
Source source = new Source();
Target target = new Target();
copyFields(source, target);
System.out.println("Target name: " + target.name); // "John"
System.out.println("Target age: " + target.age); // 30
}
}
1. 원본 객체(source)에서 필드 값을 읽음
sourceField에서 값을 가져오며, 필드 타입과 관계없이 Object 타입으로 반환한다.
2. 대상 객체(target)에 값을 설정
필드의 타입에 맞게 값을 설정한다. 내부적으로는 타입 검사와 변환이 이루어져야 하므로, 필드의 타입과 value가 일치하지 않으면 예외가 발생한다.
728x90