There are times when you wish you had some access to the information present in your Java classes. Information, such as which fields, methods and constructors are defined in it. This information is called as the metadata of a class and there is a way in which you can access easily without doing tedious coding or resorting to any hacks. It is called as Reflection.

Reflection in Java is done by using using the java.lang.Class class. This class provides access to all the information within your own applications classes or even the regular java library classes. Let’s say you have a class in a package called com.tt.company.Employee then if you need the metadata of the Employee class you would have to first assign it to the Class as :

Class c = Class.forName(“com.tt.company.Employee);

Accessing Fields, Methods and Constructors with Reflection

If you are not sure which fields and methods are declared in a class and you don’t have access to the source code then you can easily get this information by simple looping.

For example, if I wanted to access the fields and methods declared in the class Employee then its as simple as the below code.

Field[] fields = c.getFields();
 
Method[] methods = c.getMethods();
for (Field f : fields)
 
System.out.println("Field: " + f.getName());
 
for (Method m : methods)
 
System.out.println("Method:" + m.getName());

You might get some additional methods if you use the getMethods() method. This is because Read the rest of this entry »