Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java reflection API: Invoking a method without parameters

Tags:

The method I want to invoke (I know it's public but I need to use reflection):

public byte[] myMethod()   

I get the Method object like this and m contains myMethod() (I checked with the debugger)

Method m = Class.forName(MyClass.class.getName()).getDeclaredMethod("myMethod"); 

Finally I need to invoke m and pass the result to an object:

byte[] myBytes = null; m.invoke(myBytes); 

No exception is thrown but myBytes stays null... I also tried the following without more success:

m.invoke(myBytes, (Object[])null); 

How can I get the result of the invocation to myBytes?

like image 834
znat Avatar asked Jan 21 '13 17:01

znat


1 Answers

No exception is thrown but myBytes stays null

Correct, what you wanted there was:

byte[] myBytes = (byte[])m.invoke(yourInstance); 

More in the documentation. Notes:

  • The return value of the method is the return value of invoke.
  • The first argument to invoke is the instance on which to call the method (since you've listed an instance method, not a static method; if it were static, the first argument would be null). You haven't shown a variable referring to the instance anywhere, so I called it yourInstance in the above.
like image 83
T.J. Crowder Avatar answered Sep 28 '22 19:09

T.J. Crowder