Friday, March 31, 2006

Using Java Reflection

I was using reflection in Java and needed to pass an int rather than an Integer to a method. I thought it couldn't be done, but it can.

Using Java Reflection: "Setting Up to Use Reflection

The reflection classes, such as Method, are found in java.lang.reflect. There are three steps that must be followed to use these classes. The first step is to obtain a java.lang.Class object for the class that you want to manipulate. java.lang.Class is used to represent classes and interfaces in a running Java program.

One way of obtaining a Class object is to say:

Class c = Class.forName('java.lang.String');

to get the Class object for String. Another approach is to use:

Class c = int.class;

or

Class c = Integer.TYPE;

to obtain Class information on fundamental types. The latter approach accesses the predefined TYPE field of the wrapper (such as Integer) for the fundamental type."

0 Comments:

Post a Comment

<< Home