Search code examples
javaarraysobjectreflectiontyped

Assign Object array with Integer elements to Integer array


I searched the internet but didn't found any appropriate solution.

In my application I've got an array of integers. I need to access (assign to) the array via reflection. The application creates an object array that contains Integer elements. Java doesn't allow to assign this Object array to the Integer array.

Is it not possible in Java? My application only knows the Class Object of the Integer array field. The code is dynamically. The type may be an arbitrary type.

private final Integer[] destArray = new Integer[2];

public static void main(final String[] args) throws Exception {
  final ReloadDifferentObjectsTest o = new ReloadDifferentObjectsTest();
  final Object[] srcArray = {Integer.valueOf(1), Integer.valueOf(2)};
  final Field f = o.getClass().getDeclaredField("destArray");
  f.setAccessible(true);

  // first trial
  // f.set(o, srcArray);

  // second trial
  // Object tmpArray = Array.newInstance(f.getType().getComponentType(), srcArray.length);
  // tmpArray = Arrays.copyOfRange(srcArray, 0, srcArray.length);
  // f.set(o, tmpArray);

  // third trial
  Object tmpArray = Array.newInstance(f.getType().getComponentType(), srcArray.length);
  tmpArray = f.getType().getComponentType().cast(Arrays.copyOfRange(srcArray, 0, srcArray.length));
  f.set(o, tmpArray);
}

Solution

  • Ok, found the solution... I've got to set each single element via reflection:

    // fourth trial
    final Object tmpArray = Array.newInstance(f.getType().getComponentType(), srcArray.length);
    for (int i = 0; i < srcArray.length; i++) {
      Array.set(tmpArray, i, srcArray[i]);
    }
    
    f.set(o, tmpArray);