Groovy matching constructor error
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)
One of possible problems may be that there is 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.