1

リフレクション API を使用して、クラスのインスタンスからメソッドを呼び出しています。すべて問題ありません。多くのチュートリアルと公式のオラクル ドキュメントを順を追って実行しましたが、スローされ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)
4

3 に答える 3

3

I believe you need to pass the static class and not the class at runtime.

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

In the following code :

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

HttpServletRequest and HttpServletResponse are variables, thus getClass() call is subject to polymorphism.

You want to write :

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 に答える