-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDynamicMethodInvocation.java
More file actions
29 lines (24 loc) · 918 Bytes
/
DynamicMethodInvocation.java
File metadata and controls
29 lines (24 loc) · 918 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.lang.reflect.Method;
class MyService {
public void greet(String name) {
System.out.println("Hello, " + name + "!");
}
}
public class DynamicMethodInvocation {
public static void main(String[] args) {
try {
// 1. Get the Class object for MyService
Class<?> serviceClass = MyService.class;
MyService instance = new MyService();
// 2. Get the Method object by name and parameter type(s)
String methodName = "greet";
Method method = serviceClass.getMethod(methodName, String.class);
// 3. Invoke the method dynamically
String argument = "Dibya";
System.out.print("Invoking method '"+ methodName +"': ");
method.invoke(instance, argument);
} catch (Exception e) {
e.printStackTrace();
}
}
}