next up previous contents
Next: Arrays Up: Other Topics Previous: Inner and Anonymous Classes   Contents

Primitive Types

There is a Class object for every type, including class, interface, array and primitive types and void. For primitive types, Class objects are not obtained using Class.forName, instead one uses the TYPE field of the appropriate wrapper class (of which there currently are nine). For example, the class representing an int is Integer.TYPE. Note, this is a different type of class than the class representing the Integer class itself: Integer.getClass().

The class objects representing types are used when calling Class::getMethod(name, Class[] paramtypes), where the paramtypes array is used to determine the method signature. Thus, there is a difference between a method void m(Integer x) and void m(int x) and the Reflection API can handle that.

In addition to this, the API also provides for some automatic wrapping/unwrapping and widening conversions. If Field::get(), for example, is called on a field of primitive type, the value is automatically wrapped and returned as the appropriate object. Field::set(Object) works similarly to unwrap an object value if necessary. The following methods can perform these automatic wrap/unwrap operations:

Field::get() - wraps if necessary
Array::get() - wraps
Method::invoke() - unwraps parameters and wraps return value
Field::set() - unwraps
Array::set() - unwraps

Several forms of widening conversions are allowed at run-time and are performed in the same five methods above. These are the same conversions that are permitted in method invocation contexts at compile time, for example int to long. These also include widening reference conversions such as from a subclass to a superclass or from an interface to an implementing class. (Note that when you are trying to obtain a method using Class::getMethod(), then using subclasses instead of the actual classes of the declared parameters will not work.)

In addition to the generic get()/set() methods in the Field class, there are getInteger()/ getDouble()/ setFloat(), etc. which take or return primitive types so no wrapping/unwrapping is necessary.


next up previous contents
Next: Arrays Up: Other Topics Previous: Inner and Anonymous Classes   Contents
Nadeem Hamid 2000-07-24