Question

Suppose I have

 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

How to fill method variable so that it get array element by index?

Was it helpful?

Solution

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
                                   ^^^^

OTHER TIPS

Try with List

int[] array = new int[] { 1, 2, 3 };

// create a List and populate
List<Integer> list = new ArrayList<Integer>();
for (int i : array) {
    list.add(i);
}

// use reflection method get/set on List
Method method = List.class.getDeclaredMethod("get", new Class[] { Integer.TYPE });
Object element2 = method.invoke(list, 2); // reflection version

System.out.println(element2); // output 3
  • array doesn't have any get method. you can try with List.
  • Finally you can get the array back from the List
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top