No Such Method Exception in Java

Like the InvocationTargetException
(above), the NoSuchMethodException
is related to the use of reflection. This error stems from trying to access a provided method name that either does not exist or is configured as a private method. Consider the simple example below:
public class Example {
public int divide(int numerator) {
return numerator / 0;
} public int addOne(int number) {
return doSomethingPrivate(number);
} private int doSomethingPrivate(int number) {
return number++;
}
}
The doSomethingPrivate()
method is a private method and not visible in the following scenario:
Class c = Class.forName("Example");
Method method = c.getDeclaredMethod("doSomethingPrivate", parameterTypes);
method.invoke(objectToInvokeOn, params);
As a result, it throws a NoSuchMethodException
.