我正在使用反射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)发布于 2013-06-27 17:40:25
我认为你需要在运行时传递静态类,而不是类。
Class[] argTypes = new Class[2];
argTypes[0] = HttpServletRequest.class;
argTypes[1] = HttpServletResponse.class;发布于 2013-06-27 17:40:45
在以下代码中:
Class[] argTypes = new Class[2];
argTypes[0] = HttpServletRequest.getClass();
argTypes[1] = HttpServletResponse.getClass();HttpServletRequest和HttpServletResponse是变量,因此getClass()调用具有多态性。
你想写下:
Class[] argTypes = new Class[2];
argTypes[0] = HttpServletRequest.class;
argTypes[1] = HttpServletResponse.class;发布于 2013-06-27 17:51:35
您正在尝试调用类"x.xx.xxx.Default“方法(这是一个有效的类名吗?)在' object‘类型的on对象上。
我会试试这个:
YourClassType object = (YourClassType) cls.newInstance();或者类似的东西。我现在不能做一个很好的查找,但我确信你正在尝试从一个' object‘类型的对象上调用某个类型的方法,而这个对象并不知道那个特定的方法。
https://stackoverflow.com/questions/17339646
复制相似问题