Java reflection class

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.Stack
import 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.
Java swing
Java swing - What is Swing? Explain the need of Swing, features of Swing, Java Swing class hierarchy, need of Layout manager...
Java layout manager
Java layout manager - Different layout manager in Java - Border Layout, Flow Layout, Card Layout, Grid Layout, Grid Bag Layout,...
Java exception handling
Java exception handling - Explain the need of Exception handling, Exceptions categories, i.e. checked and unchecked exceptions, Provide the general form of Exception handling constructs with explanation, What is user defined Exception?,...
Post your comment