Implementation of Java Reflection Method’s invoke() Function.
The Method class in Java reflection provides an invoke method to call a method. The prototype of the invoke method is:
public Object invoke(Object obj, Object… args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException
In this, obj represents the object on which the method is called and args represent the method’s parameters.
The invoke method allows you to call any object’s method at runtime. Here is an example code:
import java.lang.reflect.Method;
public class ReflectDemo {
public static void main(String[] args) {
try {
// 获取String类的toUpperCase方法
Method method = String.class.getMethod("toUpperCase");
// 调用toUpperCase方法
String str = "hello";
Object result = method.invoke(str);
System.out.println(result); // 输出HELLO
} catch (Exception e) {
e.printStackTrace();
}
}
}
In the example above, we first use the getMethod method to obtain the toUpperCase method of the String class. Then we use the invoke method to call the toUpperCase method, passing in a string object as a parameter. Finally, we output the result of the call.