I'm having a problem while using constructors with a Groovy class.
I have a class Data
in a file called Data.groovy
with an inner class ContentEntry
. I want to initialize ContentEntry
instances from a Data
method:
static void initContent(nid, uid)
{
curContent = new ContentEntry()
curContent.nid = nid;
curContent.uid = uid;
}
with ContentEntry
defined as:
class ContentEntry
{
public int nid, uid
private tags = [:]
public ContentEntry()
{
}
ContentEntry(int nid, int uid)
{
this.nid = nid
this.uid = uid
}
//omitted rest of the class
But when running the project it gives me the following error:
Exception in thread "main" org.codehaus.groovy.runtime.metaclass.MethodSelectionException:
Could not find which method <init>() to invoke from this list:
public it.softit.Data$ContentEntry#<init>(it.softit.Data, int, int)
public it.softit.Data$ContentEntry#<init>(it.softit.Data)
It's like if constructors implicitly need an instance of the outer class passed as a parameter. I'm wondering why..
To create an object by using positional parameters, the respective class needs to declare one or more constructors. In the case of multiple constructors, each must have a unique type signature. The constructors can also added to the class using the groovy. transform.
To do this, go to the context menu of a table (or several tables) and press Scripted Extension → Generate POJO. groovy. Choose a destination folder, and that's it! The class-file is ready.
[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]
A MetaClass within Groovy defines the behaviour of any given Groovy or Java class. The MetaClass interface defines two parts. The client API, which is defined via the extend MetaObjectProtocol interface and the contract with the Groovy runtime system.
The requirement that all (non-static) inner classes need a reference to their outer class is imposed by Java, rather than Groovy. If you instantiate the inner class from a non-static method, the reference should be set to this
. However, there is no this
reference within a static method.
To fix the problem either:
Of course the constructor need a instance of the outer class. That's why inner class exist: to live only within an outer class. You cannot instanciate an inner class outside of its outer class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With