[java] 리플렉션을 사용하여 정적 메서드 호출

main정적 인 메소드 를 호출하고 싶습니다 . 유형의 객체를 얻었 Class지만 해당 클래스의 인스턴스를 만들 수 없으며 static메서드 를 호출 할 수도 없습니다 main.



답변

// String.class here is the parameter type, that might not be the case with you
Method method = clazz.getMethod("methodName", String.class);
Object o = method.invoke(null, "whatever");

이 방법이 getDeclaredMethod()대신 개인용 인 경우 getMethod(). 그리고 setAccessible(true)메소드 객체를 호출 하십시오.


답변

Method.invoke ()의 Javadoc에서 :

기본 메소드가 정적이면 지정된 obj 인수가 무시됩니다. null 일 수 있습니다.

당신은 어떻게됩니까

클래스 클라스 = ...;
방법 m = klass.getDeclaredMethod (methodName, paramtypes);
m.invoke (null, args)


답변

String methodName= "...";
String[] args = {};

Method[] methods = clazz.getMethods();
for (Method m : methods) {
    if (methodName.equals(m.getName())) {
        // for static methods we can use null as instance of class
        m.invoke(null, new Object[] {args});
        break;
    }
}


답변

public class Add {
    static int add(int a, int b){
        return (a+b);
    }
}

위의 예에서 ‘add’는 두 정수를 인수로 취하는 정적 메소드입니다.

다음 스 니펫은 입력 1과 2로 ‘add’메소드를 호출하는 데 사용됩니다.

Class myClass = Class.forName("Add");
Method method = myClass.getDeclaredMethod("add", int.class, int.class);
Object result = method.invoke(null, 1, 2);

참조 링크 .


답변