This class is quite esoteric - most uses of arrays know the type of the array, so this class is typically most useful when implementing code that handles arrays generically.
There is no array superclass for all arrays, so there is no uniform way of accessing elements or the size of an array regardless of type. The java.lang.reflect.Array
fills this gap and allows you to access the array in the same way regardless from type. For example, to get the value at a given index from any array (returned as an object).
It's parameteric polymorphism. Sure, you could code this yourself if you know the type - you just cast. If you don't know the array type, or it can be several types, you would check the possibilities and cast appropriately - which is what the code in reflect.Array
does.
EDIT: In response to the comment. Consider how you would solve this problem - how to count the number of times a value is duplicated in an array. Without the type-agnostic Array class, this would not be possible to code, without explicitly casting the array, so you would need a different function for each array type. Here, we have one function that handles any type of array.
public Map<Object, Integer> countDuplicates(Object anArray)
{
if (!anArray.getClass().isArray())
throw new IllegalArgumentException("anArray is not an array");
Map<Object,Integer> dedup = new HashMap<Object,Integer>();
int length = Array.getLength(anArray);
for (int i=0; i<length; i++)
{
Object value = Array.get(anArray, i);
Integer count = dedup.get(value);
dedup.put(value, count==null ? 1 : count+1);
}
return dedup;
}
EDIT2: Regarding the get*() and set*() methods. The source code link above links to Apache harmony. The implementation there does not adhere to the Sun Javadocs. For example, from the getInt method
@throws IllegalArgumentException If the specified object is not an array,
or if the indexed element cannot be converted to the return type
by an identity or widening conversion
This implies that the actual array could be byte[]
, short[]
or int[]
. This is not the case with the Harmony implementation, which only takes an int[]
. (Incidentally, the Sun implementation uses native methods for most of the Array class.) The get*() and set*() methods are there for the same reason as get()
, getLength()
- to provide (loosely) type-agnostic array access.
Not exactly something you need to use every day, but I imagine it provides value for those that need it.