【问题标题】:Object Array Declaration in GroovyGroovy 中的对象数组声明
【发布时间】:2018-06-16 04:31:13
【问题描述】:

为什么我不能在 Groovy 中声明 People 数组,如图所示。 可能是我对类的理解不够深入

class People {
    Integer id
}

class Job {
    def func() {
        People[] p = new People[10]
    }
}

我收到错误 People[] cannot be applied to app.People[]

【问题讨论】:

  • 不幸的是,这只是它看起来像的语言的本质......为了分配一个不在堆栈上的对象,(或者它的大小是预先确定的) - 你必须使用 def关键字

标签: groovy


【解决方案1】:

您显示的代码示例不会重现您在上述问题中提到的错误。它实际上已经损坏并且无法编译 - 方法 func() 缺少它的主体。如果您将代码更正为例如

class People {
    Integer id
}

class Job {
    def func() {
        People[] p = new People[10]
        assert p.size() == 10
        println p
    }
}

new Job().func()​

您将看到它产生了预期的结果 - 在 Groovy Web 控制台here 中查看它。当你运行它时,你会在控制台看到以下输出:

[null, null, null, null, null, null, null, null, null, null]

Groovy 和 Java 的区别

在数组初始化方面,Groovy 和 Java 之间存在一个显着差异。在 Java 中,您可以像这样初始化一个 People[] 数组:

People[] p = new People[] { new People(), new People(), /* ... */ new People() };

它在 Groovy 中不起作用,因为 Groovy 保留 {} 用于关闭。在 Groovy 中,您可以初始化这样的数组:

People[] p = [new People(), new People(), new People()] as People[]

【讨论】:

  • 嗯,我的代码中确实有括号,只是没有包含在问题中。不过感谢您的澄清!
【解决方案2】:

虽然 Szymon Stepniak 的回答对于 Groovy 2.5 及更低版本是正确的,但 Java 样式的数组初始化是新 Parrot 解析器对 Groovy 3.0 和 2.6 的增强功能的一部分。

来自release notes的示例:

def primes = new int[] {2, 3, 5, 7, 11}
assert primes.size() == 5 && primes.sum() == 28
assert primes.class.name == '[I'

def pets = new String[] {'cat', 'dog'}
assert pets.size() == 2 && pets.sum() == 'catdog'
assert pets.class.name == '[Ljava.lang.String;'

// traditional Groovy alternative still supported
String[] groovyBooks = [ 'Groovy in Action', 'Making Java Groovy' ]
assert groovyBooks.every{ it.contains('Groovy') }

【讨论】:

    【解决方案3】:

    Szymon Stepniak 的回答是正确的。我将在我工作过的一些单元测试中指出另一个真实案例的例子(一般对象类型):

    Object[] o = [YourModel] as Object[]
    

    这足以用您的模型属性模拟一个通用对象。

    【讨论】:

      猜你喜欢
      • 2013-03-22
      • 2023-04-05
      • 1970-01-01
      • 2023-04-06
      • 2019-12-02
      • 1970-01-01
      • 2015-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多