1

I am using reflection api to invoke a method from an instance of a class. everything is ok and I followed many tutorials and official oracle docs step by step but it throws NoSuchMethodException. here is my code:

// Part of the main class
    Class[] argTypes = new Class[2];
    argTypes[0] = HttpServletRequest.getClass();
    argTypes[1] = HttpServletResponse.getClass();

    Object[] args = new Object[2];
    args[0] = request;
    args[1] = response;

    try {
        Class<?> cls = Class.forName("x.xx.xxx.Default");
        Object object = cls.newInstance();
        Method method = cls.getDeclaredMethod("index", argTypes);
        method.invoke(object, args);
    } catch (Exception exception) { // for simplicity of the question, I replaced all exception types with Exception
        exception.printStackTrace();
    }

// End of the main class
    // class x.xx.xxx.Default

    public class Default {
        public void index(HttpServletRequest request, HttpServletResponse response) {
            try {
                PrintWriter writer = response.getWriter();
                writer.println("Welcome");
            } catch (IOException exception) {
                System.err.println(exception);
            }
        }
    }

and this is the description of exception which I gave when the exception happens

java.lang.NoSuchMethodException: x.xx.xxx.Default.index(org.apache.catalina.connector.RequestFacade, org.apache.catalina.connector.ResponseFacade)
4

3 回答 3

3

我相信您需要在运行时传递静态类而不是类。

Class[] argTypes = new Class[2];
argTypes[0] = HttpServletRequest.class;
argTypes[1] = HttpServletResponse.class;
于 2013-06-27T09:40:25.057 回答
2

在以下代码中:

Class[] argTypes = new Class[2];
argTypes[0] = HttpServletRequest.getClass();
argTypes[1] = HttpServletResponse.getClass();

HttpServletRequestHttpServletResponse是变量,因此getClass()call 受多态性影响。

你想写:

Class[] argTypes = new Class[2];
argTypes[0] = HttpServletRequest.class;
argTypes[1] = HttpServletResponse.class;
于 2013-06-27T09:40:45.030 回答
0

您正在尝试在“对象”类型的对象上调用类“x.xx.xxx.Default”的方法(这是一个有效的类名吗?)。

我会试试这个:

YourClassType object = (YourClassType) cls.newInstance();

或类似的东西。我现在无法进行良好的查找,但我很肯定您正在尝试从“对象”类型的对象上调用某种类型的方法,该对象不知道该特定方法。

于 2013-06-27T09:51:35.347 回答