java.lang.nosuchmethoderror – How to avoid
In this tutorial we will discuss about Java’s NoSuchMethodError
and how to deal with it. The NoSuchMethodError
is a sub-class of the LinkageError
class and denotes that an application code is trying to call a specified method of a class, either static or instance, and that class has no longer a definition for that method. This error exists since the first release of Java (1.0) and normally is caught by the compiler. However, this error can occur at run-time, if the definition of a class has incompatibly changed.
The most common case where this error is thrown is when an application code is trying to run a class, which does not have a main method. For example, suppose we have the following Java source file:
Example.java:
public class Example { /* Create two private fields. */ private String key = null; private Integer value; public Example(String key, Integer value) { this.key = key; this.value = value; } public String getKey() { return this.key; } public Integer getValue() { return this.value; } }
Now, let’s compile it using Java Compiler (Javac):
javac Example.java
Javac does not find any errors and thus, creates the bytecode file Example.class. If we try to execute it using the following command
java Example
we get the following error:
Error: Main method not found in class Example, please define the main method as: public static void main(String[] args)
Notice that we would still get the same error, if the application code does not contain a main method with the appropriate signature. The correct signature of the main method is the following:
public static void main(String[] args);
The NoSuchMethodError
error is also thrown when the referenced class used to compile the code and the class in the classpath are different. This error occur at runtime, if the definition of a class has incompatibly changed. The user must check for this error, in cases the definition of a class has incompatibly changed.
Finally, the NoSuchMethodError
error can be thrown when an application makes use of external libraries. Suppose your application is compiled and executed using a specific version of an external library. At some point, the external library is changed and some methods are removed or updated. If the classpath of your application is not updated and your code is not compiled using the latest version of the external library, then during runtime you will invoke a method that no longer exists and the NoSuchMethodError
error will be thrown.
Thus, when you compile your application be sure that your classpath contains the appropriate source and .jar
files, and that you have the latest version of each one.
This was a tutorial about Java’s NoSuchMethodError
.
How to fix the no such method in java program during run time