从groovy方法调用顶级函数 [英] Call top level function from groovy method

查看:72
本文介绍了从groovy方法调用顶级函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这是一个简单的答案,但是我的网络搜索找不到它.

I figure this has a simple answer, but my web searching couldn't find it.

如果我有以下内容( ideone ):

If I've got the following (ideone):

def f() {}

class C
{
    public h() { f() }
}

x = (new C()).h();

此操作失败,并显示以下错误:

This fails with the following error:

No signature of method: c.f() is applicable for argument types: () values: []

如何从 C 方法内部调用 f()?

推荐答案

您需要引用外部"类(实际上不是外部类).

You need a reference to the "outer" class (which isn't really an outer class).

假定您将代码编写在 Script.groovy 文件中,它将生成两个类: C.class Script.class .由于无法确定在哪里定义,因此无法通过 C 调用 f()方法.

Assuming you are writing your code in a Script.groovy file, it generates two classes: C.class and Script.class. There is no way to the C call the f() method, since it has no idea where it is defined.

您有一些选择:

1) @MichaelEaster的想法,从当前范围(即 Script )给出元类定义

1) @MichaelEaster's idea, giving a metaclass defition from the current scope (i.e. Script)

2) C 内创建/传递 Script 对象:

2) Create/pass a Script object inside C:

def f() { "f" }

class C
{
    public h(s = new Script()) { s.f() }
}

assert "f" == new C().h()

3) C 设置为内部类(还需要 Script 的实例:

3) Make C an inner class (which also needs an instance of Script:

class Script {
  def f() { "f" }

  class C
  {
      public h() { f() }
  }

  static main(args) {
    assert "f" == new C(new Script()).h()
  }
}

4):静态内部类以及静态 f():

4) Static inner class plus static f():

class Script {
  static def f() { "f" }

  static class C
  {
      public h() { f() }
  }

  static main(args) {
    assert "f" == new C().h()
  }
}

这篇关于从groovy方法调用顶级函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆