Section 7.3. Reflection for Primitive Types


7.3. Reflection for Primitive Types

Every type in Java, including primitive types and array types, has a class literal and a corresponding class token.

For instance, int.class denotes the class token for the primitive type for integers (this token is also the value of the static field Integer.TYPE). The type of this class token cannot be Class<int>, since int is not a reference type, so it is taken to be Class<Integer>. Arguably, this is an odd choice, since according to this type you might expect the calls int.class.cast(o) and int.class.newInstance() to return values of type Integer, but in fact these calls raise an exception. Similarly, you might expect the call

 java.lang.reflect.array.newInstance(int.class,size) 

to return a value of type Integer[], but in fact the call returns a value of type int[]. These examples suggest that it might have made more sense to give the class token int.class the type Class<?>.

On the other hand, int[].class denotes the class token for arrays with components of the primitive type integer, and the type of this class token is Class<int[]>, which is permitted since int[] is a reference type.




Java Generics and Collections
Java Generics and Collections
ISBN: 0596527756
EAN: 2147483647
Year: 2006
Pages: 136

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net