What is a Java NoSuchMethodException?

Java exception FAQ: What is a Java NoSuchMethodException?

Answer: Using Java, you can get a NoSuchMethodException when you're using reflection and try to dynamically use a method on a class, and the method does not actually exist. The following example Java class shows how this NoSuchMethodException can be generated:

package com.devdaily.javasamples;

import java.lang.reflect.Method;

public class JavaReflectionExample2
{

  public JavaReflectionExample2()
  {
    Class c;
    try
    {
      c = Class.forName("java.lang.String");
      try
      {
        Class[] paramTypes = new Class[5];
        Method m = c.getDeclaredMethod("fooMethod", paramTypes);
      }
      catch (SecurityException e)
      {
        e.printStackTrace();
      }
      catch (NoSuchMethodException e)
      {
        e.printStackTrace();
      }
    }
    catch (ClassNotFoundException e)
    {
      // deal with the exception here ...
      e.printStackTrace();
    }
  }

  public static void main(String[] args)
  {
    new JavaReflectionExample2();
  }

}

In this example I intentionally create a NoSuchMethodException by trying to instantiate a method named fooMethod on the java.lang.String class. Here's the line of code that actually throws the exception:

Method m = c.getDeclaredMethod("fooMethod", paramTypes);

Because this method (fooMethod) doesn't exist, a NoSuchMethodException is thrown. The actual error message (stack trace) is as follows:

java.lang.NoSuchMethodException: java.lang.String.fooMethod(null, null, null, null, null)
   at java.lang.Class.getDeclaredMethod(Class.java:1909)
   at com.devdaily.javasamples.JavaReflectionExample2.(JavaReflectionExample2.java:17)
   at com.devdaily.javasamples.JavaReflectionExample2.main(JavaReflectionExample2.java:37)

Share it!

There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.