リフレクション 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)