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.

--

--

--

Tech enthusiastic, life explorer, single, motivator, blogger, writer, software engineer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Mhp3 English Patch 3.9.1 Download

Microservices: an explosion of metrics and few insights?

Understanding Python (Part-1)

Build Serverless App & CI/CD pipeline w/ AWS SAM & GitHub Actions

ProximaX 1st. Quarter, 2019 — Review by Lon Wong

Cartesi Labs: Building a More Accessible Future for Smart Contract Development

CSS clamp() Function for Responsive Fonts

Thinkium four layer technology

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
TechGuy

TechGuy

Tech enthusiastic, life explorer, single, motivator, blogger, writer, software engineer

More from Medium

#01 Code Refactoring Shortcuts in IntelliJ

Date and Time In Java

Complete guide to modules in java

Inheritance In Java -10 Program