[英]How to load a class function outside declaring class in Java Reflections
我正在使用Java Reflections 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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.