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: One problem I encountered when trying to invoke the method is how to specify the type of its argument. My method receives one argument and its type is Map. Therefore I cannot do Map<User, String>.TYPE
(In run time there's no such a thing as Map because of Java Type erasure). Is there another way to get the method?
Invoke main from reflection tutorial
Let's say you want to call MyClass.myMethod(int x);
No, you can't say
Map<K,V>.class
. This is because of type erasure. At runtime, there's no such thing.Luckily, you can say just plain old
Map.class
. It's all the same at runtime.If the warnings bother you, search for other questions related to generics and type erasure, there's a wealth of information on the subject here.
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.
I use a single method that encapsulates getting the target method and then invoking it. Probably has some limitations, of course. Here is the method put into a class and its JUnit test:
}