- 获取目标类的
Class
对象。
- 使用
Class
对象的 getMethods()
或 getDeclaredMethods()
方法获取方法数组。
getMethods()
返回一个 Method
类型的数组,包含所有公共(public)方法,包括从父类继承的方法。
getDeclaredMethods()
返回一个 Method
类型的数组,包含类声明的所有方法,包括公共(public)、保护(protected)、默认(包)访问和私有(private)方法,但不包括继承的方法。
- 遍历方法数组,找到你想要调用的方法。
- 使用
Method
对象的 invoke()
方法调用该方法。
import java.lang.reflect.Method;
public class ReflectionDynamicCall {
public static void main(String[] args) {
try {
// 步骤1: 获取Class对象
Class<?> cls = Class.forName("java.util.Date");
// 步骤2: 获取所有公共方法
Method[] methods = cls.getMethods();
// 步骤3: 遍历方法数组
for (Method method : methods) {
if (businessService.equals(method.getName())) {
// 动态调用方法
Object instance = cls.getDeclaredConstructor().newInstance();
ProxyRechargeResponse result = (ProxyRechargeResponse) method.invoke(instance);
return result.getRespParams();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
评论区