Difference between NoSuchMethodException and NoSuchMethodError in Java

99封情书 提交于 2019-12-05 12:52:26

问题


I can't find exact difference between NoSuchMethodException and NoSuchMethodError in Java. Could someone give explanation and example of these two things ?


回答1:


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.)




回答2:


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




回答3:


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)




回答4:


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.



来源:https://stackoverflow.com/questions/27938776/difference-between-nosuchmethodexception-and-nosuchmethoderror-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!