Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs
How can I invoke a static method dynamically without an instance reference? Method.invoke(Object obj, Object[] parms) needs a concrete instance, but I want to call the static method directly on a Class object! Is this possible in Java?
The workaround is to create an instance dynamically with newInstance() and call invoke with that instance, but this will not work if the class does not have an empty constructor. And I don't want to create instances
I really don't need!
According to the JDK API documentation for Method.invoke(Object obj, Object[] args), "If the underlying method is static, then the specified obj argument is ignored. 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.
The following sample program tests this fact, and correctly produces the output below. A concrete instance of class Foo is never created.
import java.lang.reflect.*;
public class Test
{
public static void main(String[] args)
{
try
{
Class c = Class.forName("Foo");
System.out.println("Loaded class: " + c);
Method m = c.getDeclaredMethod("getNum", null);
System.out.println("Got method: " + m);
Object o = m.invoke(null, null);
System.out.println("Output: " + o);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
class Foo
{
public static int getNum()
{
return 5;
}
}
Program output:
Loaded class: class Foo Got method: public static int Foo.getNum() Output: 5