Groovy Runtime Exception: Could not find matching constructor

If you encounter an exception like this:

groovy.lang.GroovyRuntimeException: Could not find matching constructor for: com.example.BaseClass$InnerClass(...)
        at YourClass.yourMethod(YourClass.groovy:20)

Then you most likely have a class InnerClass, which is declared inside BaseClass:

class BaseClass {
  class InnerClass {
    InnerClass(...) {
      // Your constructor
    }
  }
}

And in some other class (even inherited from BaseClass) you are trying to instantiate InnerClass:

class YourClass extends BaseClass {
  def yourMethod() {
    InnerClass inner = new InnerClass(...)
  }
}

Then you will get groovy.lang.GroovyRuntimeException: Could not find matching constructor. The point is that objects of inner classes in groovy need to be created using a method in the wrapper class. Let’s add the corresponding method to BaseClass:

class BaseClass {
  def createInnerClass(...) {
    return new InnerClass(...)
  }

  class InnerClass {
    InnerClass(...) {
      // Your constructor
    }
  }
}

And in YourClass we use the newly created createInnerClass() method:

class YourClass extends BaseClass {
  def yourMethod() {
    InnerClass inner = createInnerClass(...)
  }
}

After that, the exception will disappear.

If you still have any questions, feel free to ask me in the comments under this article, or write me on promark33@gmail.com.

If I saved your day, you can support me :)

Leave a Reply

Your email address will not be published.