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

前端 未结 5 442
[愿得一人]
[愿得一人] 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:55

    Object insecure; //This needs to be an initialized reference
    
    Class c = insecure.getClass();
    Method m = c.getMethod(name, parameterTypes); //Fill the name and types in
    m.setAccessible(true);
    m.invoke( insecure, parameters ); //Fill in the parameters you would like
    

    There are a number of checked exceptions which may be thrown. Both parameterTypes and parameters are ellipse arguments (variable length), fill them in as needed. The JVM by specification has a strongly typed calling convention so you need to know the parameter types.

    With that said, unless you are writing some sort of application container, server component container, RMI-like system, or JVM based langauge you should avoid doing this.

提交回复
热议问题