Difference between NoSuchMethodException and NoSuchMethodError in Java

前端 未结 4 1420
礼貌的吻别
礼貌的吻别 2021-02-19 01:47

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

4条回答
  •  萌比男神i
    2021-02-19 02:25

    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

提交回复
热议问题