How do I invoke a private static method using reflection (Java)?

前端 未结 5 443
[愿得一人]
[愿得一人] 2020-11-29 03:32

I would like to invoke a private static method. I have its name. I\'ve heard it can be done using Java reflection mechanism. How can I do it?

EDIT:

5条回答
  •  臣服心动
    2020-11-29 03:40

    Let's say you want to call MyClass.myMethod(int x);

    Method m = MyClass.class.getDeclaredMethod("myMethod", Integer.TYPE);
    m.setAccessible(true); //if security settings allow this
    Object o = m.invoke(null, 23); //use null if the method is static
    

提交回复
热议问题