I want to invoke the main
method which is static. I got the object of type Class
, but I am not able to create an instance of that class and also not able to invoke the static
method main
.
We can invoke a static method by using its class reference. An instance method is invoked by using the object reference.
A static method in Java (also called class method) is a method that belongs to the class and not the instance. Therefore, you can invoke the method through the class instead of creating an instance first and calling the method on that instance.
It may be null." So, instead of passing in an actual object, a null may be passed; therefore, a static method can be invoked without an actual instance of the class.
A static method can be called directly from the class, without having to create an instance of the class. A static method can only access static variables; it cannot access instance variables. Since the static method refers to the class, the syntax to call or refer to a static method is: class name. method name.
// 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");
In case the method is private use getDeclaredMethod()
instead of getMethod()
. And call setAccessible(true)
on the method object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With