[java] 리플렉션을 사용한 객체 복사

리플렉션(Reflection)은 실행 중인 애플리케이션의 클래스나 인터페이스 등을 조사하거나 조작할 수 있는 기능을 제공합니다. 이를 사용하여 객체를 복사할 수 있습니다. 주로 Object.clone() 메서드를 사용하여 객체를 복사하지만, 이 메서드를 사용하는 것은 권장되지 않거나 Cloneable 인터페이스를 구현해야 하기 때문에 리플렉션을 사용하여 객체를 복사하는 방법을 알아보겠습니다.

1. 객체 복사를 위한 메서드 작성

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class ObjectCopier {
    public static <T> T copy(T source) throws IllegalAccessException, InstantiationException {
        @SuppressWarnings("unchecked")
        Class<T> clazz = (Class<T>) source.getClass();
        T copy = clazz.newInstance();

        for (Field field : clazz.getDeclaredFields()) {
            if (!Modifier.isStatic(field.getModifiers())) {
                field.setAccessible(true);
                field.set(copy, field.get(source));
            }
        }

        return copy;
    }
}

위의 코드는 제네릭 메서드 copy를 통해 객체를 복사하는 예제입니다. Class 객체를 사용하여 리플렉션을 수행하고, 각 필드의 값을 복사합니다.

2. 객체 복사 예제

public class Person {
    private String name;
    private int age;

    // ... 생성자, 접근자 등 생략 ...

    public static void main(String[] args) throws IllegalAccessException, InstantiationException {
        Person person1 = new Person("John", 25);
        Person person2 = ObjectCopier.copy(person1);

        System.out.println(person2.getName());  // 출력: John
        System.out.println(person2.getAge());   // 출력: 25
    }
}

Person 클래스의 인스턴스 person1을 생성한 후, ObjectCopier를 사용하여 이를 복사하여 새로운 인스턴스 person2를 만들 수 있습니다.

이렇게 리플렉션을 사용하여 객체를 복사할 수 있습니다. 하지만 이러한 방식은 프로그램의 성능에 영향을 미치므로 객체 복사가 필요한 경우에는 적절히 고려하여 사용해야 합니다.

참조