Introduction
Method class is part of Java Reflection API in java.lang.reflect package. It represents a method and allows inspection and invocation of methods at runtime.
Basics of Method Class
import java.lang.reflect.Method;
class Student {
public void display() {
System.out.println("Student display");
}
public void setName(String name) {
System.out.println("Name: " + name);
}
}
public class Main {
public static void main(String[] args) {
// Get Class object
Class<?> studentClass = Student.class;
// Get all methods
Method[] methods = studentClass.getMethods();
System.out.println("Methods in Student class:");
for (Method method : methods) {
System.out.println(method.getName());
}
}
}
Getting Methods
1. Get All Public Methods:
import java.lang.reflect.Method;
class Example {
public void method1() { }
public void method2() { }
private void method3() { }
}
public class Main {
public static void main(String[] args) {
Class<?> clazz = Example.class;
// Get all public methods (including inherited)
Method[] methods = clazz.getMethods();
for (Method m : methods) {
System.out.println(m.getName());
}
}
}
2. Get Declared Methods:
// Get all methods (public, private, protected, default)
Method[] methods = clazz.getDeclaredMethods();
for (Method m : methods) {
System.out.println(m.getName());
}
3. Get Specific Method:
try {
Method method = clazz.getMethod("methodName", parameterTypes);
System.out.println("Found: " + method.getName());
} catch (NoSuchMethodException e) {
System.out.println("Method not found");
}
Method Information
import java.lang.reflect.Method;
class Calculator {
public int add(int a, int b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) throws Exception {
Method method = Calculator.class.getMethod("add", int.class, int.class);
// Get method name
System.out.println("Name: " + method.getName());
// Get return type
System.out.println("Return Type: " + method.getReturnType());
// Get parameter types
Class<?>[] paramTypes = method.getParameterTypes();
System.out.print("Parameters: ");
for (Class<?> type : paramTypes) {
System.out.print(type.getName() + " ");
}
System.out.println();
// Get modifiers
System.out.println("Modifiers: " + method.getModifiers());
}
}
Invoking Methods
import java.lang.reflect.Method;
class Student {
public void display(String name) {
System.out.println("Hello, " + name);
}
public int add(int a, int b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) throws Exception {
Student student = new Student();
// Get method
Method displayMethod = Student.class.getMethod("display", String.class);
// Invoke method
displayMethod.invoke(student, "John");
// Method with return value
Method addMethod = Student.class.getMethod("add", int.class, int.class);
Object result = addMethod.invoke(student, 10, 20);
System.out.println("Result: " + result);
}
}
Complete Example
import java.lang.reflect.Method;
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private void secretMethod() {
System.out.println("This is private");
}
}
public class Main {
public static void main(String[] args) throws Exception {
Person person = new Person("John", 25);
// Get all public methods
Method[] methods = Person.class.getMethods();
System.out.println("Public Methods:");
for (Method method : methods) {
if (method.getDeclaringClass() == Person.class) {
System.out.println("- " + method.getName());
}
}
System.out.println();
// Invoke methods
Method displayMethod = Person.class.getMethod("display");
displayMethod.invoke(person);
Method getNameMethod = Person.class.getMethod("getName");
String name = (String) getNameMethod.invoke(person);
System.out.println("Retrieved name: " + name);
Method setNameMethod = Person.class.getMethod("setName", String.class);
setNameMethod.invoke(person, "Alice");
displayMethod.invoke(person);
}
}
Method Modifiers
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
class Example {
public void publicMethod() { }
private void privateMethod() { }
protected void protectedMethod() { }
static void staticMethod() { }
final void finalMethod() { }
}
public class Main {
public static void main(String[] args) {
Method[] methods = Example.class.getDeclaredMethods();
for (Method method : methods) {
int modifiers = method.getModifiers();
System.out.print(method.getName() + ": ");
if (Modifier.isPublic(modifiers)) {
System.out.print("public ");
}
if (Modifier.isPrivate(modifiers)) {
System.out.print("private ");
}
if (Modifier.isProtected(modifiers)) {
System.out.print("protected ");
}
if (Modifier.isStatic(modifiers)) {
System.out.print("static ");
}
if (Modifier.isFinal(modifiers)) {
System.out.print("final ");
}
System.out.println();
}
}
}
Accessing Private Methods
import java.lang.reflect.Method;
class Secret {
private void privateMethod() {
System.out.println("Private method called");
}
}
public class Main {
public static void main(String[] args) throws Exception {
Secret secret = new Secret();
// Get private method
Method method = Secret.class.getDeclaredMethod("privateMethod");
// Make it accessible
method.setAccessible(true);
// Invoke
method.invoke(secret);
}
}
Method Parameters
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
class Calculator {
public int add(int firstNumber, int secondNumber) {
return firstNumber + secondNumber;
}
}
public class Main {
public static void main(String[] args) throws Exception {
Method method = Calculator.class.getMethod("add", int.class, int.class);
// Get parameters
Parameter[] parameters = method.getParameters();
System.out.println("Method: " + method.getName());
System.out.println("Parameters:");
for (Parameter param : parameters) {
System.out.println("- Name: " + param.getName());
System.out.println(" Type: " + param.getType());
}
}
}
Exception Handling
import java.lang.reflect.Method;
class Example {
public void riskyMethod() throws Exception {
throw new Exception("Something went wrong");
}
}
public class Main {
public static void main(String[] args) {
try {
Example obj = new Example();
Method method = Example.class.getMethod("riskyMethod");
// Check exceptions
Class<?>[] exceptions = method.getExceptionTypes();
System.out.println("Throws: ");
for (Class<?> ex : exceptions) {
System.out.println("- " + ex.getName());
}
// Invoke (handle exception)
method.invoke(obj);
} catch (Exception e) {
System.out.println("Error: " + e.getCause());
}
}
}
Practical Use: Dynamic Method Call
import java.lang.reflect.Method;
class Operations {
public void operation1() {
System.out.println("Operation 1");
}
public void operation2() {
System.out.println("Operation 2");
}
public void operation3() {
System.out.println("Operation 3");
}
}
public class Main {
public static void main(String[] args) throws Exception {
Operations ops = new Operations();
// Dynamic method name from user input
String methodName = "operation2"; // Could be from scanner
// Get and invoke method dynamically
Method method = Operations.class.getMethod(methodName);
method.invoke(ops);
}
}
Common Methods of Method Class
| Method | Description |
|---|---|
getName() | Get method name |
getReturnType() | Get return type |
getParameterTypes() | Get parameter types |
invoke(obj, args) | Invoke method |
getModifiers() | Get modifiers |
getDeclaringClass() | Get declaring class |
getExceptionTypes() | Get exceptions thrown |
setAccessible(true) | Access private methods |
Quick Reference
import java.lang.reflect.Method;
// Get methods
Method[] methods = clazz.getMethods(); // Public
Method[] allMethods = clazz.getDeclaredMethods(); // All
Method method = clazz.getMethod("name", params); // Specific
// Method info
String name = method.getName();
Class<?> returnType = method.getReturnType();
Class<?>[] paramTypes = method.getParameterTypes();
// Invoke method
Object result = method.invoke(object, arguments);
// Private method
method.setAccessible(true);
method.invoke(object);
Benefits
- Dynamic method calls: Call methods by name
- Inspection: Examine class structure
- Frameworks: Used in Spring, Hibernate
- Testing: Test private methods
- Plugins: Load and call methods dynamically
Limitations
- Performance: Slower than direct calls
- Security: Can bypass access control
- Type safety: No compile-time checks
- Complexity: More code, harder to read
Exam Tips
Remember:
- Method class in
java.lang.reflect - Used for reflection
getMethods()- public methodsgetDeclaredMethods()- all methodsinvoke()to call methodsetAccessible(true)for private- Returns Object, needs casting
- Used in frameworks
- Slower than direct calls
- Part of Reflection API
Common Questions:
- What is Method class?
- How to get methods?
- How to invoke methods?
- How to access private methods?
- What is reflection?
- Uses of Method class?
- getMethods() vs getDeclaredMethods()?
- Benefits and limitations?