質問

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);
}
役に立ちましたか?

解決 3

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);

他のヒント

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[].

Yes, the type of a Java array is covariantly linked to its element type. Specifically, Object[] is a supertype of Integer[] and as such is not assignment-compatible with it. You must create an Integer[] at the outset to be able to assign it to an Integer[]-typed variable. From your posted code I can see no reason why you would not do that.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top