Explain about Java reflection class.
1. Classes, interfaces, methods, instance variables can be inspected at runtime by using reflection class
2. To inspect he names of the classes, methods, fields etc. need not be known
3. Reflection in Java is powerful and useful, when objects are needed to be mapped into tables in a database at runtime.
4. Java reflection is useful to map the statements in a scripting language to that of method calls on objects at runtime.
5. Reflection in Java invokes methods of another class dynamically at run time.
Write a code sample to depict the uses of Java reflection class.
Send java.util.Stack as a command line argument:
java ReflectionExample java.util.Stackimport java.lang.reflect.*;
public class ReflectionExample
{
public static void main(String args[])
{
try
{
Class cls = Class.forName(args[0]);
Method methods[] = cls.getDeclaredMethods();
for (int index = 0; index < methods.length; index++)
System.out.println(methods[index].toString());
}
catch (Throwable exp)
{
System.err.println(exp);
}
}
}
The produced result on the console is
public java.lang.Object java.util.Stack.push(java.lang.Object)
public synchronized java.lang.Object java.util.Stack.pop()
public synchronized java.lang.Object java.util.Stack.peek()
public boolean java.util.Stack.empty()
public synchronized int java.util.Stack.search(java.lang.Object)
The complete signature of all methods of Stack class are listed.