这个类非常深奥 - 数组的大多数使用都知道数组的类型,因此在实现一般处理数组的代码时,这个类通常最有用。
没有适用于所有数组的数组超类,因此无论类型如何,都没有统一的方法来访问元素或数组的大小。这java.lang.reflect.Array
填补了这一空白,并允许您以相同的方式访问数组,无论类型如何。例如,从任何数组中获取给定索引处的值(作为对象返回)。
It's 参数多态性 http://en.wikipedia.org/wiki/Type_polymorphism#Parametric_polymorphism。当然,如果您知道类型,您可以自己编写代码 - 您只需进行强制转换。如果您不知道数组类型,或者它可以是多种类型,您将检查可能性并进行适当的转换 - 这就是代码中的内容reflect.Array
does.
编辑:回应评论。考虑如何解决这个问题 - 如何计算一个值在数组中重复的次数。如果没有与类型无关的 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 http://java.sun.com/javase/6/docs/api/java/lang/reflect/Array.html#getInt(java.lang.Object,%20int) 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
这意味着实际的数组可以是byte[]
, short[]
or int[]
。 Harmony 实现的情况并非如此,它只需要int[]
。 (顺便说一句,Sun 实现对大多数 Array 类使用本机方法。) get*() 和 set*() 方法的存在原因与get()
, getLength()
- 提供(松散的)类型不可知的数组访问。
不完全是你每天都需要使用的东西,但我想它为那些需要它的人提供了价值。