Getting the field "length" in a Java array using reflection
There is an special java.lang.reflect.Array
Class. length
is no normal field. To access it there is a special method getLength
.
I think this might be a bug in the JVM implementation. Here is my reasoning:
According to the documentation for
Class.getField
,getField
should, as part (1) of its search algorithm, findlength
if it was declared as a public field: "If C declares a public field with the name specified, that is the field to be reflected."According to the Java Language Specification, every array has
length
declared as "The public final field length, which contains the number of components of the array."Since this field is declared as having name
length
,getField
should either throw aSecurityException
as documented, or should return theField
object.
Now interestingly, the Class.getFields
method explicitly mentions that "The implicit length field for array class is not reflected by this method. User code should use the methods of class Array to manipulate arrays." This does not seem to parallel getField
, so this could either be a misreading on my part or just bad documentation.
Hope this helps!
In Java, arrays are just simple objects. Object don't have any field called length. That's why the reflection is failing.
Please see http://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html for more information on how arrays are implemented.
From the documentation ...
An array's length is not part of its type.