java - 使用反射 api 时抛出 NoSuchMethodException

标签 java exception reflection

我正在使用反射 api 从类的实例调用方法。一切正常,我一步一步地遵循了许多教程和官方 oracle 文档,但它抛出 NoSuchMethodException。这是我的代码:

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

这是我在异常发生时给出的exception的描述

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

最佳答案

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

Class[] argTypes = new Class[2];
argTypes[0] = HttpServletRequest.class;
argTypes[1] = HttpServletResponse.class;

关于java - 使用反射 api 时抛出 NoSuchMethodException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17339646/

相关文章:

java - 为什么 TreeSet 抛出 ClassCastException?

java - 在 DB2 上使用其他模式的 Hibernate 多对一

java - 在java中使用slick2D库的xml FileNotFoundException

java - 无法解析的日期 : "Apr 5, 2018" in Java

java - 未捕获异常处理程序中的未捕获异常

vb.net - 反射 - 类内数组的 SetValue?

java - 如何使用任意数量的参数调用 Method.invoke?

java - 服务器 415 响应代码

尝试连接到 gmail IMAP 服务器时出现 javax.mail.MessagingException

java - 使用 Java Reflections 获取通用类字段类型