1

我是 groovy 的新手,我正在阅读gretty项目的源代码

import org.codehaus.jackson.map.ObjectMapper
class JacksonCategory {
static final ObjectMapper mapper = []
    ...
}

我看不懂代码ObjectMapper mapper = [],这里是什么[]意思?我以为它是 a list,但是如何将它分配给 a ObjectMapper


更新

就看沙丘的回答了,好像[]是手段invocation of default constructor。所以,这意味着:

static final ObjectMapper mapper = new ObjectMapper()

但:

String s = []
println s // -> it's `[]` not ``

Integer i = []

抛出异常:

Caught: org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object '[]' 
with class 'java.util.ArrayList' to class 'java.lang.Integer' 
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object '[]' with class  
'java.util.ArrayList' to class 'java.lang.Integer'
4

1 回答 1

6

这是对 ObjectMapper 的默认构造函数的调用。

http://mrhaki.blogspot.com/2009/09/groovy-goodness-using-lists-and-maps-as.html

它似乎[]总是被创建为一个空的 ArrayList,但是当分配给一个单独的类型时,groovy 会尝试进行类型强制并找到一个合适的构造函数。

对于字符串,它只调用列表中的 toString 方法并将其变为字符串。对于对象,它会寻找具有适当数量和类型的参数的构造函数。

Groovy 不希望对扩展 Number(Integer、BigDecimal 等)并抛出 ClassCastException 的 java 库类执行此操作。

例子:

class A {
    String value;
    A() { this("value"); }
    A(String value) { this.value = value; }
}

def A defaultCons = [];
// equivalent to new A()
def A argsCons = ["x"];
// equivalent to new A("x")
def list = [1,2];
// literal ArrayList notation
def String str = [];
// equivalent to str = "[]"

println "A with default constructor: " + defaultCons.value;
println "A with String arg constructo: " + argsCons.value;
println "list: " + list;
println "str: " + str;
于 2011-08-20T08:23:03.077 回答