21
votes

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?

3

3 Answers

33
votes

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.
13
votes

You're currently passing the value of myBytes into the method - as if it's the target object you'd be calling it on. It's the return value.

You want:

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

where target is the instance you want to call it on (as it's an instance method).

If you don't have an instance, the method will have to be a static method, at which point you'd change the invocation to:

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

invoke method takes first argument as instance object for the method followed by parameters. Here method signature is public byte[] myMethod()

Code to invoke myMethod:

byte[] returnVal = (byte[]) m.invoke(MyClass.newInstance());