programing

반사를 사용하여 정적 메서드 호출

prostudy 2022. 4. 29. 23:12
반응형

반사를 사용하여 정적 메서드 호출

I want to incall the operation.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)방법의 목적에 따라

메소드의 자바독으로부터.호출():

기본 방법이 정적인 경우 지정된 obj 인수는 무시된다.무효일지도 모른다.

네가 할 때 무슨 일이 일어나니?

클래스 클라스 = ...;방법 m = klas.getDeclaredMethod(methodName, parametype);
m.dv(m.dv, 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);

참조 링크.

참조URL: https://stackoverflow.com/questions/2467544/invoking-a-static-method-using-reflection

반응형