这个类非常深奥 - 数组的大多数用途都知道数组的类型,因此这个类通常在实现一般处理数组的代码时最有用。
所有数组都没有数组超类,因此无论类型如何,都没有统一的访问元素或数组大小的方法。 java.lang.reflect.Array 填补了这一空白,并允许您以相同的方式访问数组,而不管类型如何。例如,从任何数组(作为对象返回)中获取给定索引处的值。
它是parameteric polymorphism。当然,如果您知道类型,您可以自己编写代码 - 您只需进行转换。如果您不知道数组类型,或者它可能有多种类型,您将检查可能性并进行适当的转换 - 这就是 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;
}
EDIT2:关于 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() 相同 - 提供(松散的)类型 -不可知的数组访问。
不完全是你每天都需要使用的东西,但我想它为那些需要它的人提供了价值。