Java reflection API: Invoking a method without parameters

javareflection

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?

Best Answer

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.