获取场"长度QUOT;在使用Java反射阵列 [英] Getting the field "length" in a Java array using reflection
问题描述
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;
};
当我运行上面的code,我得到的命令行上以下结果 -
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?
推荐答案
我认为这可能是在JVM实现中的错误。这里是我的推理:
I think this might be a bug in the JVM implementation. Here is my reasoning:
-
据的的文档
Class.getField
,getfield命令
应作为部分(1)其搜索算法,找到长度
如果它被声明为public字段:如果是C声明了指定名称的公共领域,就是要体现场
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."
根据的规格 Java语言中,每个阵列有长度
宣布为公众最后一个字段的长度,其中包含数组的组件数量。
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."
由于该字段被声明为名称长度
, getfield命令
要么抛出一个 SecurityException异常
如记录,还是应该返回字段
对象。
Since this field is declared as having name length
, getField
should either throw a SecurityException
as documented, or should return the Field
object.
现在有趣的是, Class.getFields
法明确提到,对于数组类的隐式长度字段是不是用这种方法反映出来。用户code应该使用类的方法数组操作数组。这似乎并不平行 getfield命令
,所以这可能要么是我的一个误读或只是坏的文档。
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.
希望这有助于!
这篇关于获取场"长度QUOT;在使用Java反射阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!