Where is array's length property defined?

前端 未结 7 919
悲哀的现实
悲哀的现实 2020-11-22 13:41

We can determine the length of an ArrayList using its public method size(), like

ArrayList arr = new ArrayL         


        
7条回答
  •  被撕碎了的回忆
    2020-11-22 14:21

    It's "special" basically, with its own bytecode instruction: arraylength. So this method:

    public static void main(String[] args) {
        int x = args.length;
    }
    

    is compiled into bytecode like this:

    public static void main(java.lang.String[]);
      Code:
       0:   aload_0
       1:   arraylength
       2:   istore_1
       3:   return
    

    So it's not accessed as if it were a normal field. Indeed, if you try to get it as if it were a normal field, like this, it fails:

    // Fails...
    Field field = args.getClass().getField("length");
    System.out.println(field.get(args));
    

    So unfortunately, the JLS description of each array type having a public final field length is somewhat misleading :(

提交回复
热议问题