Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

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

Dynamically invoking a static method without instance reference (July 6, 1999)

The JavaWorld experts answer your most pressing Java questions -- every week

  • Print
  • Feedback

QHow 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!

AAccording 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:

About the author

Random Walk Computing is the largest Java/CORBA consulting boutique in New York, focusing on solutions for the financial enterprise. Known for their leading-edge Java expertise, Random Walk consultants publish and speak about Java in some of the most respected forums in the world.
Loaded class: class Foo
Got method: public static int Foo.getNum()
Output: 5


  • Print
  • Feedback

Resources