`ObjectMapper mapper = []`在groovy中意味着什么?

时间:2011-08-20 07:55:33

标签: groovy gretty

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

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

我不理解代码ObjectMapper mapper = [][]在这里是什么意思?我认为这是list,但如何将其分配给ObjectMapper


更新

取决于Dunes's answer,似乎[]表示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'

1 个答案:

答案 0 :(得分:6)

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

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

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

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

对于扩展Number(Integer,BigDecimal等)并抛出ClassCastException的java库类,Groovy不希望这样做。

示例:

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;