Java Program to list all the method of any class using reflection.
Objective
Write a Java program to list all the methods of any given class using Reflection.
Algorithm / Approach
- Prompt the user for a fully qualified class name (e.g.,
java.util.TimerTask). - Use
Class.forName(classname)to dynamically load the class into memory. - Call
c.getDeclaredMethods()to get an array of all methods inside the class. - Loop through the
Method[]array and print each method signature.
IDETool.java
import java.lang.reflect.*;
import java.util.*;
public class IDETool {
public static void main(String args[])
{
try {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Class Name:");
String classname = sc.nextLine();
Class c = Class.forName(classname);
Method[] m = c.getDeclaredMethods();
for (int i = 0; i < m.length; i++)
System.out.println(m[i].toString());
}
catch (Throwable e){
System.err.println(e);
}
}
}
Expected Output
Enter Class Name: java.util.TimerTask protected java.util.TimerTask(); public abstract void run(); public boolean cancel(); public long scheduledExecutionTime();
Explanation of the Program
- Reflection is one of the most powerful and advanced features of Java. It allows a Java program to inspect, analyze, and even modify itself at runtime.
- Without knowing what the class is at compile time, we can ask the JVM to load the class, extract its DNA (its methods, fields, and constructors), and expose them to us. This technique is heavily used by frameworks like Spring and Hibernate to auto-wire dependencies.
Complexity
Time Complexity
O(m) - Where m is the number of methods in the class.
Space Complexity
O(m) - To store the Method array.