Open ywbestPark opened 10 months ago
import java.lang.reflect.Method;
public class DynamicMethodInvocationWithParameters {
public static void main(String[] args) {
try {
// 클래스 이름과 메서드 이름을 입력받음
String className = "YourClassName"; // 대상 클래스 이름
String methodName = "yourMethodName"; // 실행할 메서드 이름
// 클래스를 동적으로 로드
Class<?> targetClass = Class.forName(className);
// 메서드를 동적으로 가져옴
Method method = targetClass.getMethod(methodName, String.class, int.class); // 예시: 문자열과 정수 파라미터
// 인스턴스 생성 (기본 생성자를 사용할 경우)
Object instance = targetClass.getDeclaredConstructor().newInstance();
// 메서드 실행에 필요한 인수 설정
String inputParam1 = "Example Input";
int inputParam2 = 42;
// 메서드 실행
Object result = method.invoke(instance, inputParam1, inputParam2);
// 결과 출력
System.out.println("Method result: " + result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
public class DynamicConstructorInvocation {
public static void main(String[] args) {
try {
// 클래스 이름을 입력받음
String className = "YourClassName"; // 대상 클래스 이름
// 클래스를 동적으로 로드
Class<?> targetClass = Class.forName(className);
// 생성자 인수 타입을 결정 (예시: String, int)
Class<?>[] constructorParameterTypes = {String.class, int.class};
// 생성자 가져오기
Constructor<?> constructor = targetClass.getConstructor(constructorParameterTypes);
// 생성자를 사용하여 객체 인스턴스 생성
Object instance = constructor.newInstance("Example Input", 42);
// 실행할 메서드 이름을 입력받음
String methodName = "yourMethodName"; // 실행할 메서드 이름
// 실행할 메서드의 시그니처를 결정 (예시: String, int)
Class<?>[] methodParameterTypes = {String.class, int.class};
// 메서드 가져오기
Method method = targetClass.getMethod(methodName, methodParameterTypes);
// 메서드 실행에 필요한 입력 파라미터 설정
Object[] methodArgs = {"Method Input", 123};
// 메서드 실행
Object result = method.invoke(instance, methodArgs);
// 결과 출력
System.out.println("Method result: " + result);
} catch (Exception e) {
e.printStackTrace();
}
}
}