java - 使用反射获取Java数组中的字段 "length"

标签 java arrays 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;
};

当我运行上面的代码时,我在命令行上得到以下结果 --

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)

为什么我无法访问数组中的“length”字段?

最佳答案

有一个特殊的java.lang.reflect.Array类(class)。 length 不是普通字段。要访问它,有一个特殊的方法 getLength

关于java - 使用反射获取Java数组中的字段 "length",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11097658/

相关文章:

java - hibernate 和 JPA : how to make a foreign key constraint on a String

java - jsoup 只去除 html 标签而不是换行符?

java nio 否定 glob 模式

javascript - 制作对象数组时的封装问题

javascript - 比较数组中存储的对象的属性

java - 将jar文件复制到webapp文件夹中的maven项目中

arrays - Ruby 数组哈希值问题

java.lang.NoSuchMethodException : Unknown property 异常

c# - 需要反射帮助 : GetProperty Returns Unexpected Type

java - 使用runtime.exec()调用java方法