Reputation: 4516
I understand that for every primitive type in java there is a reference type that can represent the same values, plus null. For example, int and java.lang.Integer.
I also understand that while all arrays (even java.lang.Object[]) derive from java.lang.Object, only arrays of non-primitive types can be converted to java.lang.Object[].
In other words, we can do:
Class type = Integer.class;
Object[] o = (Object[])java.lang.reflect.Array.newInstance(type, 4);
but the following results in an exception:
Class type = int.class;
Object[] o = (Object[])java.lang.reflect.Array.newInstance(type, 4);
so in that particular case we could do:
Class type = int.class;
Object o = java.lang.reflect.Array.newInstance(type, 4);
...which seems fine, until one wonders how to add elements to an Object that represents an array that cannot be converted to Object[].
is the only way around this problem to check the type of the elements of the array and cast the Object as appropriate?
ie:
if (type == int.class)
((int[])o)[0] = getFirstElement();
else if (type == short.class)
((short[])o[0] = getFirstElement();
Upvotes: 2
Views: 309
Reputation: 6897
Besides creating arrays, java.lang.reflect.Array
also offers methods to get and set elements in arrays:
Class<?> type = int.class;
Object array = java.lang.reflect.Array.newInstance(type, 4);
int index = 0;
Object value = getFirstElement();
java.lang.reflect.Array.set(array, index, value);
Also note from the documentation that the value is first automatically unwrapped if the array has a primitive component type.
So this should work for any array, including those that do not inherit from Object[]
.
There is a corresponding Object get(Object array, int index)
method too.
Upvotes: 1
Reputation: 47729
Well, in the first case you can assign to Object and then use isInstanceOf Object[]
to see if you have an array of Object.
But ultimately you have to have some sort of conditional operation to do element access/assignment. Thankfully there are only (IIRC) 7 different scalar data types.
(The language spec could have defined the Integer/Float/et al to include array member access methods -- eg, Integer would define get and set methods for int[]
. But they didn't. At best you could define wrappers for the (alas, final) Number subclasses to define these methods.)
Upvotes: 1