I can't find exact difference between NoSuchMethodException
and NoSuchMethodError
in Java. Could someone give explanation and example of these two things ?
Class NoSuchMethodErrorThrown if an application tries to call a specified method of a class (either static or instance), and that class no longer has a definition of that method. Normally, this error is caught by the compiler; this error can only occur at run time if the definition of a class has incompatibly changed.
NoSuchMethodError is a runtime error in Java which occurs when a method is called that exists at compile-time, but does not exist at runtime. The Java Garbage Collector (GC) cannot free up the space required for a new object, which causes a java. lang. OutOfMemoryError .
Dig into the do. something code, decompiling it if you don't have the source, and see what is actually thrown by it. Possibly if the exception gets thrown it might get wrapped in another exception. Make sure that anything thrown by the method does not get eaten (including by your own logging of it).
NoSuchMethodError: main Exception in thread "main" can come due to various reasons like: 1) The class which you are trying to run doesn't have the main method. 2) The signature of the main method is not correct.
NoSuchMethodException can be thrown when you're invoking a method through reflection, and the name of the method comes from a variable in your program.
NoSuchMethodError can be thrown when a compiled Java class does a regular method call to another class and the method doesn't exist. (This usually happens when the caller class was compiled against one version of the class being called, and is being executed together with another version of that class, which no longer has the method.)
NoSuchMethodException
occurs when you try to invoke a method using reflection.
NoSuchMethodError
occurs when you had that method while compiling but dont have it during the runtime.
Consider the following example for NoSuchMethodError
Class : Person.java
public class Person{
public String getName(){
return "MyName";
}
}
Compile it using
javac Person.java
And now try to run this using
java Person
It ll give you
java.lang.NoSuchMethodError: main
Exception in thread "main"
Because it tries to find the public static void main(String [] args)
which is not there
For NoSuchMethodException
c = Class.forName("java.lang.String");
try
{
Class[] paramTypes = new Class[2];
Method m = c.getDeclaredMethod("myMethod", paramTypes);
}
this is ll throw an exception saying
java.lang.NoSuchMethodException: java.lang.String.myMethod(null, null)
Consider this link which has a better explaination
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With