Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using reflection to call static method for return value [duplicate]

Possible Duplicate:
How do I invoke a private static method using reflection (Java)?

So there is a method named something along the lines of "getInstance" which just returns an instance of a certain class. It's a static method with no arguments.

How could I call that method, and get the return value (the instance) of the class? Every method I try to use requires me to have an instance of the class in the arguments it seems.

For example, I try to use

Method method = classLoader.loadClass("testClass").getMethod("getInstance", null);
            Object object = method.invoke(null, null);

but I always get a null pointer exception at this line,

Object object = method.invoke(null, null);

Which I'm assuming I get since the object it asks for is null.

Thanks for any help.

Edit: Method is not null. I am doing a System.out.println(method == null); and it prints out false.

like image 594
Austin Avatar asked Apr 18 '26 10:04

Austin


1 Answers

You don't want null as your argument or parameter list. Instead you can do

Method method = classLoader.loadClass("testClass").getMethod("getInstance", new Class[0]);
Object object = method.invoke(null, new Object[0]);

or the following as they are varargs methods.

Method method = classLoader.loadClass("testClass").getMethod("getInstance");
Object object = method.invoke(null);
// or works but is perhaps confusing.
Object object = method.invoke(null, null);
like image 73
Peter Lawrey Avatar answered Apr 20 '26 02:04

Peter Lawrey