I can\'t find exact difference between NoSuchMethodException
and NoSuchMethodError
in Java. Could someone give explanation and example of these two th
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.)
Class NoSuchMethodException:
Thrown when a particular method cannot be found.
Class NoSuchMethodError
Thrown 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.
Also see this article, it explains it better.
NoSuchMethodException
is thrown when you try and get a method that doesn't exist with reflection. E.g. by calling Class#getDeclaredMethod(name, parameters)
with either the wrong name or parameters.
NoSuchMethodError
is thrown when the virtual machine cannot find the method you are trying to call. This can happen when you compile with one version of a library, and later run the application with another version of the library on the classpath (e.g. an older one that doesn't have the method you're calling)
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