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);
}
Jon Skeet
people
quotationmark

No, you can't cast a value which is actually a reference to an instance of Object[] to an Integer[] variable - and that's a good thing. Imagine if that were valid... consider:

Object[] values = { new Integer(5), new Integer(10) };
Integer[] integers = values;
Integer x = integers[0]; // Okay so far

values[0] = new Object(); // Sneaky!
Integer y = integers[0]; // ??? This would have to fail!

If you want to cast something to Integer[], it has to actually be an Integer[]. So this line:

final Object[] srcArray = {Integer.valueOf(1), Integer.valueOf(2)};

... needs to change to create an instance of Integer[].

people

See more on this question at Stackoverflow