Java reflection; how to use Method.invoke() to retrieve an Object array

javareflection

I need some help using reflection in Java. I need to use reflection to call a method that returns an Object array. Method.invoke() only returns an Object. How is this done?

Many thanks for any insights!

Best Answer

You just have to cast the return value of Method.invoke() to whatever you happen to know it is. Not very robust, but such are the risks of reflection! So in this case, it would be:

Object[] result = (Object[]) method.invoke(...);

Btw, note that if the method returns a primitive (int, double, etc), Method.invoke will return its boxed equivalent (Integer, Double, etc).