简体   繁体   中英

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

I am using java reflections API to load my functions dynamically from a variable.When i was calling the functions in the same class,the function calls were working.

Now i am trying to call functions outside the declaring class.This is the code i am using.

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

I am trying to acess a different class and the functions and i get the following error.

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

The exception is because of this line val=method.invoke(this, instInputText,request).toString(); .

You are passing this as an instance to the call, which means it will perform something like this.method() . Instead you need to create an instance of class Actions and use that in place of this .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM