Groovy构造函数

Jac*_*ack 12 groovy constructor

我在使用带有Groovy类的构造函数时遇到了问题.

Data在一个Data.groovy用内部类调用的文件中有一个类ContentEntry.我想ContentEntryData方法初始化实例:

static void initContent(nid, uid)
{
    curContent = new ContentEntry()
    curContent.nid = nid;
    curContent.uid = uid;
}
Run Code Online (Sandbox Code Playgroud)

ContentEntry定义为:

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
Run Code Online (Sandbox Code Playgroud)

但是在运行项目时它会给我以下错误:

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)
Run Code Online (Sandbox Code Playgroud)

这就像构造函数隐式需要作为参数传递的外部类的实例一样.我想知道为什么..

Dón*_*nal 9

要求所有(非静态)内部类需要对其外部类的引用是由Java而不是Groovy强加的.如果从非静态方法实例化内部类,则应将引用设置为this.但是,this静态方法中没有引用.

要解决这个问题:

  • 从非静态方法实例化内部类
  • 使内部类静态.然后,您可以从任何地方实例化它(但它将不再具有对外部类的实例的引用).