Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking a static method using reflection

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.

like image 745
Steven Avatar asked Mar 18 '10 04:03

Steven


People also ask

How do we invoke static methods?

We can invoke a static method by using its class reference. An instance method is invoked by using the object reference.

Can you invoke a static method from an instance?

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.

Can a static method invoke a static method?

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.

How do you call a static method in Java?

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.


1 Answers

// 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.

like image 126
Adeel Ansari Avatar answered Sep 18 '22 11:09

Adeel Ansari