这个异常通常在使用 getDeclaredMethod
方法时抛出,表示在指定的类中找不到所需的方法。下面是一个解决此异常的示例代码:
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
try {
Method method = getDeclaredMethod("add", Integer.class);
System.out.println("Method found: " + method.getName());
} catch (NoSuchMethodException e) {
System.out.println("Method not found: " + e.getMessage());
}
}
public static Method getDeclaredMethod(String methodName, Class>... parameterTypes) throws NoSuchMethodException {
Class listClass = ArrayList.class;
try {
Method method = listClass.getDeclaredMethod(methodName, parameterTypes);
return method;
} catch (NoSuchMethodException e) {
throw new NoSuchMethodException("Method not found: " + methodName);
}
}
}
在上面的示例中,我们定义了一个 getDeclaredMethod
方法,该方法接受方法名和参数类型作为参数,并尝试在 ArrayList
类中查找相应的方法。如果找到了方法,则返回该方法;否则,抛出 NoSuchMethodException
异常并提供相应的错误消息。
在 main
方法中,我们调用 getDeclaredMethod
方法并捕获可能抛出的异常。如果找到了方法,我们输出方法名;否则,输出相应的错误消息。