A Practical Use of Java's Reflection API
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.
Consider a system that does custom processing on packets
of data. What processing will be done on the data depends
upon the value of the header field of the packet. What will you
do if the processing requirements are dynamic in
nature and values that the header-field can
have keep changing depending upon customer requirements etc?
The above problem can be conveniently solved using Reflection.
Reflection API enables you to create an instance of a class
whose name is not known until runtime. You can just plug-in the
custom processing classes into the system, without having to
recompile the code again.
All the processing classes will be derived from the same
base class 'MessageProcessor'.
public abstract class MessageProcessor
{
public abstract void runProcessing(Object message);
}
public class ProcessingOne extends MessageProcessor
{
public void runProcessing(Object message)
{
System.out.println("Processing type one");
}
}
|
The system that is processing the packets, reads the
packet header and calls the required processing as shown
below:
{
:
String processName;
MessageProcessor messageProcessor;
:
:
processName = message.header;
//Assuming the header is of String type and
//gives the full name of the class
Class class = Class.forName(processName);
messageProcessor =
(MessageProcessor).class.newInstance();
messageProcessor.runProcessing(message);
}
|
You can download sample program here to compile and play with it.
You can add new 'Processor classes' even at runtime. The system, will insantiate it
on receiving appropriate packet/header.