Reflection question: Why is length not a field of an array?

I

Ian A. Mason

The Java Language Specification says (10.7 page 197)

"The members of an array type are all of the following"

* The public final field length ...
* The public method clone which overrides ...
* All the members inherited from the class Object; ...

....

"

Yet if one tries to access that field via reflection, it isn't there.
(Nor is the public clone method that is supposed to be there.)
It seems only to be accessible via the Array.getLength method. Any
*real* reason for this? For doubting thomases:

import java.lang.reflect.Field;
import java.lang.reflect.Array;
import java.lang.reflect.Method;

public class ArrayLength {
public static void main(String[] args){
Object target = new int[10];
Class targetClass = target.getClass();
Field field;
try {
field = targetClass.getField("length");
}catch(NoSuchFieldException e){
System.err.println("No such field: " + e);
}catch(SecurityException e){
System.err.println("Security exception: " + e);
}
/* look for the length field */
Field[] fields = targetClass.getFields();
System.err.println("fields.length = " + fields.length);
/* nope */
/* OK get it the other way */
System.err.println("array length = " + Array.getLength(target));
/* what about the methods inherited from Object */
Method[] methods = targetClass.getMethods();
System.err.println("methods.length = " + methods.length);
/* OK looks right */
/* a public clone is supposed to be here as well */
Method[] dmethods = targetClass.getDeclaredMethods();
System.err.println("declared methods.length = " + dmethods.length);
/* nope not there either */
}
}
 
T

Tor Iver Wilhelmsen

Yet if one tries to access that field via reflection, it isn't there.

Correct: The "Java-the-language" array length "field" is turned into a
call to the "Java-the-VM" instruction arraylength.

In effect, it's syntactic sugar, much like the Foo.class "static
field" which does not exist either (though the compiler will
synthesize a method class$(String) which wraps a call to
Class.forName()).
 
C

Chris Uppal

Tor said:
Correct: The "Java-the-language" array length "field" is turned into a
call to the "Java-the-VM" instruction arraylength.

In effect, it's syntactic sugar

Yes, and a bloody stupid idea too...

-- chris
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,049
Latest member
Allen00Reed

Latest Threads

Top