Besides creating objects of a class and calling constructors/methods on that object, accessing the properties/variables of the class, theres is something else which can be done with the classes. The reflection is a reflection of a class as seen by the JVM. The JVM will see a class as having some methods,constructors,instance variables etc. The mother of reflection API is the Class class. For every class that is present in a program or provided by SUN as part of java API, there exists an instance of Class class for that class. This may sound strange, but lets take and example.
Say I have created a class named foo in the project as:
public class foo {
foo() {}
_ _ _ _ _ _
_ _ _ _ _ _
}
Now i create bar class to give a feeling of the reflection API.
public class bar{
foo f1 = Class.forName("foo"); //created the foo object
}
Please note that the class bar is declared as public and hence is obviously in some other project/package.
We never imported the foo class to create an object of it. That was possible because of the reflection API and the Class class.
The bottomline of all this discussion is that a instance of the Class class reflects any class.
Now we modify the bar class as shown below:
import foo; //modify as per your project settings.
public class bar{
foo f1 = Class.forName("foo"); //created the foo object
Class c1 = foo.class;
java.lang.reflect.Constructor[] const1 = c1.getConstructors();
System.out.println(const1[0].getName());
}
Here we get the instance of the Class class corresponding to the foo class and then get an array of its constructors by invoking the method getConstructors() on it and then display the name of the first constructore present in the foo class.
I hope this has made things more clear and now you can browse the java.lang.reflect package to know more about what can be done with the reflection API.
But there is a word of caution with using the reflection API because all this happens at runtime, the performance may be effected because of over using the reflection API.