我正在尝试使用代码段:
GenericModel.class.getDeclaredMethod("findById");
Run Code Online (Sandbox Code Playgroud)
获得一个名为“findById”的方法。我知道该方法存在,因为当我调用时:
GenericModel.class.getDeclaredMethods();
Run Code Online (Sandbox Code Playgroud)
该方法列在返回的数组中。
但是,当使用第一个代码段时,我得到了 java.lang.NoSuchMethodException?为什么?
据推测,findById实际上需要参数。但是您正在寻找一个不带任何名称的方法。最有可能你想要的是:
GenericModel.class.getDeclaredMethod("findById", new Class[] { int.class });
Run Code Online (Sandbox Code Playgroud)
这将匹配具有如下签名的方法:
Object findById(int id) { ... }
Run Code Online (Sandbox Code Playgroud)