The Reflection API allows Java code to examine classes and objects at run time. The new reflection classes allow you to call another class's methods dynamically at run time.
Another practical use is that many times you are not able to tell exactly which class will be instantiated, until the runtime. In these situations you want to be able to create an object through some identifier such as the name of the class. This is one of the abilities that Reflection API of Java provides.
Reflection allows you toget details from an object whose class you don't know. You can get its name, method details, fields, constructors, and print them on screen. We are having a discussion on the Advanced Java forum at the moment. See if you can understand it. The "second version of the go() method" will print out class name, and a list of methods, on screen. I made a mistkae with what I posted; the serialize() method should be changed so the "try" block reads like this:-and similarly the "try" block in the go() method should be changed like this:-
The reason for the "finally" blocks is so as to make sure you get the ObjectInputStream and ObjectOutputStream properly closed, even if something goes wrong and there is an exception in the inner "try" blocks. Otherwise you leave them open until you exit Java, which can lead to the file being unavailable for other applications, or even a memory leak.
Reflection is particularly useful to people who are writing IDEs and similar apps; they can analyse the class in development and print out lists of methods. The diagrams you see on IDEs where the methods are in different colours are made using a similar technique.
You will see, on the "advanced" thread I mentioned, that the discussion is about whether it is possible to de-serialize or analyse a class whose original programming one can't get at, and so far we haven't found a way to do it.
Frameworks and tools make use of reflection more often than normal business code. For example to make a tool to generate XML from any object you can use reflection to get a list of public fields and get their values, or get a list of getXXX() methods and call them.
Then you might write another million lines of business code dealing with customers and airplane reservations and pineapples without another line of reflection.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi