외부 설정 기반의 반사 기반 객체 생성 및 메서드 실행 프레임워크

어플리케이션 외부에서 클래스 정보와 동작을 제어할 수 있는 경량 프레임워크를 구현하되, 대상 클래스의 소스 코드를 일체 수정하지 않는 것을 목표로 한다. 이는 반사(Reflection) API를 활용해 런타임에 클래스를 동적으로 로드하고, 인스턴스를 생성하며, 지정된 메서드를 호출하는 방식으로 구현된다.

핵심 설계 원칙은 다음과 같다:

  • 대상 클래스는 public 접근자만 갖는 기본 생성자와 공개 메서드를 포함해야 하며, 별도 어노테이션이나 인터페이스 구현 없이 사용 가능하다.
  • 클래스 이름과 실행할 메서드 이름은 외부 설정 파일(.properties 또는 .txt)에 선언되며, 코드 내 하드코딩을 배제한다.
  • 모든 반사 작업은 예외 처리를 통해 안정성과 디버깅 용이성을 확보한다.

다음은 실제 구현 예시이다. 설정 파일 app-config.properties에는 다음과 같은 내용이 있다:

target.class=org.example.runtime.DemoService
target.method=launch

이 설정을 기반으로 동작하는 프레임워크 엔트리 포인트는 다음과 같다:

package org.example.runtime;

import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

public class RuntimeInvoker {

    public static void executeFromConfig() throws Exception {
        // 1. 설정 파일 로드
        Properties config = new Properties();
        try (InputStream is = RuntimeInvoker.class
                .getClassLoader()
                .getResourceAsStream("app-config.properties")) {
            if (is == null) {
                throw new IllegalArgumentException("설정 파일 'app-config.properties'를 찾을 수 없습니다.");
            }
            config.load(is);
        }

        // 2. 설정값 추출
        String targetClassName = config.getProperty("target.class");
        String targetMethodName = config.getProperty("target.method");

        if (targetClassName == null || targetMethodName == null) {
            throw new IllegalArgumentException("필수 설정 값 'target.class' 또는 'target.method'가 누락되었습니다.");
        }

        // 3. 클래스 로딩 및 인스턴스 생성
        Class<?> targetClass = Class.forName(targetClassName);
        Constructor<?> defaultConstructor = targetClass.getDeclaredConstructor();
        Object instance = defaultConstructor.newInstance();

        // 4. 메서드 조회 및 실행
        Method targetMethod = targetClass.getDeclaredMethod(targetMethodName);
        targetMethod.setAccessible(true); // private 메서드도 허용하려면 필요 (선택 사항)
        targetMethod.invoke(instance);
    }

    public static void main(String[] args) {
        try {
            executeFromConfig();
        } catch (Exception e) {
            System.err.println("실행 중 오류 발생: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

대상 클래스는 다음과 같이 단순히 정의될 수 있다:

package org.example.runtime;

public class DemoService {
    public void launch() {
        System.out.println("서비스가 성공적으로 시작되었습니다.");
    }
}

위 구현은 Class.forName(), getDeclaredConstructor().newInstance(), getDeclaredMethod().invoke()를 조합하여 외부 설정에 따라 유연하게 동작하도록 설계되었으며, 컴파일 타임에 어떤 클래스도 의존하지 않는다.

태그: java-reflection properties-configuration java-runtime dependency-injection-lightweight

10월 13일 09:17에 게시됨