开发者

What does `ObjectMapper mapper = []` mean in groovy?

I'm new to groovy, and I'm reading the source of a project gretty

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

I don't understand the code ObjectMapper mapper = [], what does [] mean here? I thought it's a list, but how to assign it to a ObjectM开发者_Go百科apper?


UPDATE

Depends on Dunes's answer, seems [] means invocation of default constructor. So, it means:

static final ObjectMapper mapper = new ObjectMapper()

But:

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

And

Integer i = []

throws exception:

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'


It's a call to the default constructor of ObjectMapper.

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

It seems [] is always created as an empty ArrayList, but when assigned to a separate type groovy tries to do type coercion and find an appropriate constructor.

With strings it just calls the toString method on the list and makes that the string. For objects it looks for constructors with the appropriate number and type of arguments.

Groovy does not expect to have to do this for java library classes that extend Number (Integer, BigDecimal, etc) and throws a ClassCastException instead.

Examples:

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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜