Java Method Class & invoke() Explained
In Java, the Method class represents a method. It provides methods that can be used to retrieve and manipulate information about the method.
Common methods of the Method class include:
- getName(): obtain the name of the method.
- getReturnType(): Obtain the return type of the method.
- getParameterTypes(): Retrieve the parameter types of a method.
- getModifiers():获取方法的修饰符。
- invoke(Object obj, Object… args): calling a method.
invoke(Object obj, Object… args) is one of the most important methods in the Method class. It is used to call a method, with the first parameter obj being the caller of the method, and the following args being the method’s arguments.
Here is an example code using the Method class and invoke method:
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args) throws Exception {
// 获取Person类的sayHello方法
Method method = Person.class.getMethod("sayHello", String.class);
// 创建Person对象
Person person = new Person();
// 调用sayHello方法
method.invoke(person, "Tom");
}
}
class Person {
public void sayHello(String name) {
System.out.println("Hello, " + name + "!");
}
}
In the above code, the getMethod method is first used to retrieve the sayHello method of the Person class. Then, a Person object is created and the invoke method is used to call the sayHello method, passing in the parameter “Tom”. Finally, the sayHello method will output “Hello, Tom!”.
It is important to note that when using the invoke method, one must handle exceptions because the invoke method may throw IllegalAccessException or InvocationTargetException exceptions.