Invoking a static method using reflection
Asked Answered
D

5

241

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.

Disgraceful answered 18/3, 2010 at 4:33 Comment(0)
J
347
// 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.

Jamaaljamaica answered 18/3, 2010 at 4:41 Comment(0)
D
56

Fromthe Javadoc of Method.invoke():

If the underlying method is static, then the specified obj argument is ignored. It may be null.

What happens when you

Class klass = ...;
Method m = klass.getDeclaredMethod(methodName, paramtypes);
m.invoke(null, args)
Daniels answered 18/3, 2010 at 4:41 Comment(1)
what if m is a method that recive a method or Callable interface as parameterAchromic
M
17
String methodName= "...";
String[] args = {};

Method[] methods = clazz.getMethods();
for (Method m : methods) {
    if (methodName.equals(m.getName())) {
        // for static methods we can use null as instance of class
        m.invoke(null, new Object[] {args});
        break;
    }
}
Meggy answered 18/3, 2010 at 4:38 Comment(5)
Why not use getMethod with the correct name instead of looping through all the methods?Kythera
Sometimes it's much easier to loop and find the method by name than to use getMethod because getMethod (or getDeclaredMethod) requires that you work out the parameter types in great detail. It just depends if micro efficiency matters - Java iteration is very quick so unless you're calling the method millions of times in some inner loop then iteration will be fast enoughCerf
Also in a more real-life situation you would probably only be finding the method once even if you're going to use reflection to invoke it multiple times. So extra overhead when finding it is immaterial.Kaye
Gonna have a bad time with overloaded methods though.Opec
@UlysseMizrahi it all depends on what you match on, but yes if you're writing library code, it can be dangerous to only rely on name. I usually check for a specific annotation, or a particular method signature, like "static method that takes a String and returns an instance of the class", then assert that there is only one such method found.Gulosity
D
6
public class Add {
    static int add(int a, int b){
        return (a+b);
    }
}

In the above example, 'add' is a static method that takes two integers as arguments.

Following snippet is used to call 'add' method with input 1 and 2.

Class myClass = Class.forName("Add");
Method method = myClass.getDeclaredMethod("add", int.class, int.class);
Object result = method.invoke(null, 1, 2);

Reference link.

Dubbing answered 3/4, 2020 at 8:59 Comment(0)
P
-1

Please keep in mind, that you have to also provide argument types, when trying to get desired method.

Below an example written using Groovy.

import groovy.transform.CompileStatic
import org.springframework.util.ReflectionUtils

import java.lang.reflect.Method

@CompileStatic
class Fun {

    final static String funText() {
        return 'Have fun now!'
    }

    final static String myText(String text) {
        return text
    }

}

Method m1 = ReflectionUtils.findMethod(Fun, 'funText')
println m1.invoke(null)

Method m2 = ReflectionUtils.findMethod(Fun, 'myText', String)
println m2.invoke(null, 'Some text.')

Method m3 = ReflectionUtils.findMethod(Fun, 'myText')
println m3.invoke(null, 'Another text.')

On example below m3 will fail as there is no such method.

Precast answered 22/12, 2022 at 12:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.