这个类相当深奥 — 大多数数组的用法都知道数组的类型,所以在实现处理数组通用代码时,此类通常是最有用的。
没有一个适用于所有数组的数组超类,因此无论类型如何,访问元素或数组的大小的统一方式都不存在。 java.lang.reflect.Array
填补了这一空白,并允许您以相同的方式访问数组,而不受类型的限制。例如,要从任何数组中获取给定索引处的值(作为对象返回)。
这是参数多态性。当然,如果您知道类型,可以自己编写此代码 - 只需进行强制转换即可。如果您不知道数组类型,或者它可以有几种类型,那么您将检查可能性并适当进行转换 - 这就是reflect.Array
中的代码所做的。
编辑:针对评论回复。考虑如何解决这个问题 - 如何计算数组中重复值的次数。如果没有类型不可知的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;
}
编辑2:关于get*()和set*()方法。上面的源代码链接指向Apache harmony。那里的实现不遵守Sun Javadocs。例如,从getInt方法中
@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
这意味着实际的数组可以是
byte[]
、
short[]
或
int[]
。但是Harmony实现并非如此,它只接受
int[]
。(顺便提一下,Sun实现大多数Array类使用本地方法。)
get*()
和
set*()
方法存在的原因与
get()
、
getLength()
相同——提供松散类型的数组访问。可能不是每天都需要使用,但我想它对那些需要它的人提供了价值。