Reflections: What am I doing wrong here?

Given the object:

publicclass TestObject

{

public Object[] oArray;

publicint[] iArray;

}

and the code

TestObject to =new TestObject();

Field objectArrayField = to.getClass().getField("oArray");

Object oArray = Array.newInstance(objectArrayField.getType(), 0);

objectArrayField.set(to, oArray);

Field intArrayField = to.getClass().getField("iArray");

Object iArray = Array.newInstance(intArrayField.getType(), 0);// <-- Exception on this line

intArrayField.set(to, iArray);

I am getting the following exception:

java.lang.IllegalArgumentException

at sun.reflect.UnsafeObjectFieldAccessorImpl.set(Unknown Source)

at java.lang.reflect.Field.set(Unknown Source)

at com.efw.cp.ObjectParser.main(ObjectParser.java:151)

For the life of me, I can't see what I am doing wrong. This always fails whether the int[] array is defined to an array or defined to be null.

Any ideas?

[1332 byte] By [cvweiss__a] at [2007-11-27 8:53:48]
# 1

You quite surely want to access the field's component type, not the field's type:

- objectArrayField.getType() returns the class for an array of Object

- intArrayField.getType() returns the class for an array of int

You surely want:

- objectArrayField.getType() returns the class for Object

- intArrayField.getType().getComponentType() returning the class for int

stefan.schulza at 2007-7-12 21:11:52 > top of Java-index,Core,Core APIs...
# 2
> - intArrayField.getType().getComponentType()That does the trick.Thank you.
cvweiss__a at 2007-7-12 21:11:52 > top of Java-index,Core,Core APIs...
# 3
There is a typo. Of course, you want the same method for the objectArrayField, too. It should have been:- object ArrayField.getType().getComponentType()
stefan.schulza at 2007-7-12 21:11:52 > top of Java-index,Core,Core APIs...