侧边栏壁纸
博主头像
suringYu

走走停停

  • 累计撰写 62 篇文章
  • 累计创建 20 个标签
  • 累计收到 13 条评论

目 录CONTENT

文章目录

java动态的调用类的某一个方法

suringYu
2024-10-29 / 0 评论 / 0 点赞 / 66 阅读 / 243 字
  1. 获取目标类的 Class 对象。
  2. 使用 Class 对象的 getMethods() 或 getDeclaredMethods() 方法获取方法数组。
    • getMethods() 返回一个 Method 类型的数组,包含所有公共(public)方法,包括从父类继承的方法。
    • getDeclaredMethods() 返回一个 Method 类型的数组,包含类声明的所有方法,包括公共(public)、保护(protected)、默认(包)访问和私有(private)方法,但不包括继承的方法。
  3. 遍历方法数组,找到你想要调用的方法。
  4. 使用 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();
        }
    }
}

0

评论区