如何在 Java 反射中声明 class 之外加载 class 函数

How to load a class function outside declaring class in Java Reflections

我正在使用 java 反射 API 从 variable.When 中动态加载我的函数 我在同一个 class 中调用函数,函数调用正常.

现在我正在尝试调用声明之外的函数 class.This 是我正在使用的代码。

   package com.test.controller;
   try
   {
     Class cls = Class.forName("com.test.Actions");
     System.out.println("trying to get method name");
     java.lang.reflect.Method method=cls.getMethod(action,String.class,HttpServletRequest.class);
     System.out.println("got method name"+method);
     val=method.invoke(this, instInputText,request).toString();
    }
    catch(Exception e){e.printStackTrace();}

我正在尝试访问不同的 class 和函数,但出现以下错误。

java.lang.IllegalArgumentException: object is not an instance of declaring class

异常是因为这一行val=method.invoke(this, instInputText,request).toString();

您正在将 this 作为实例传递给调用,这意味着它将执行类似 this.method() 的操作。相反,您需要创建 class Actions 的实例并使用它代替 this.