gpt4 book ai didi

java - 如何在 Java Reflections 中声明类之外加载类函数

转载 作者:行者123 更新时间:2023-12-02 04:33:12 26 4
gpt4 key购买 nike

我正在使用java反射API从变量动态加载我的函数。当我调用同一个类中的函数时,函数调用正在工作。

现在我试图调用声明类之外的函数。这是我正在使用的代码。

   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();}

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

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

最佳答案

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

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

关于java - 如何在 Java Reflections 中声明类之外加载类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31176263/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com