To answer question from title:
Java doesn't add new methods to arrays. Only methods available from arrays are those inherited from Object
class, and there is none like array.get(index)
which we could use via:
method.invoke(array,index)
That is why reflection package has utility class java.lang.reflect.Array
, which contains methods like public static Object get(Object array, int index)
and overloaded versions for primitive types like public static int getInt(Object array, int index)
. It also contains corresponding set(array, index, value)
methods.
With those we can write code like
int[] array = new int[] {1, 2, 3};
int element2 = Array.getInt(array, 2);//reflective way
//or
//int element2 = (int) Array.get(array, 2);//reflective way
System.out.println(element2);
BUT if goal of your question is to solve puzzle where we need to fill the blank and let below code work
int[] array = new int[] {1, 2, 3};
Method method = ...................// something
// int element2 = array[2]; // non-reflection version
int element2 = (int) method.invoke(array, 2); // reflection version
then probably author of puzzle wants you to reflectively call Arrays.get(array,index)
. In other words method
should represent
Method method = Array.class.getDeclaredMethod("get", Object.class, int.class);
But this would also require calling that method either on Array.class
or on null
(since it is static), so we would also need to modify
int element2 = (int) method.invoke(array, 2);
and add as first argument
int element2 = (int) method.invoke(Array.class, array, 2); // reflection version
^^^^^^^^^^^
OR
int element2 = (int) method.invoke(null, array, 2); // reflection version
^^^^