
java动态的调用类的某一个方法
- 获取目标类的
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();
}
}
}
本文是原创文章,采用 CC BY-NC-ND 4.0 协议,完整转载请注明来自 surfingYu
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果