class Test {
public static void main(String[] args) throws Exception {
Test t = new Test();
System.out.println(t.field);
System.out.println(t.getClass().getField("field").get(t));
int[] ar = new int[23];
System.out.println(ar.length);
System.out.println(ar.getClass().getField("length").get(ar));
}
public int field = 10;
};
When I run the above code, I get the following result on the command line —
10
10
23
Exception in thread "main" java.lang.NoSuchFieldException: length
at java.lang.Class.getField(Class.java:1520)
at Test.main(Test.java:9)
How come I am unable to access the field “length” in the array?
I think this might be a bug in the JVM implementation. Here is my reasoning:
According to the documentation for
Class.getField,getFieldshould, as part (1) of its search algorithm, findlengthif 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
lengthdeclared as “The public final field length, which contains the number of components of the array.”Since this field is declared as having name
length,getFieldshould either throw aSecurityExceptionas documented, or should return theFieldobject.Now interestingly, the
Class.getFieldsmethod 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 parallelgetField, so this could either be a misreading on my part or just bad documentation.Hope this helps!