What does `ObjectMapper mapper = []` mean in groov

2019-08-04 09:23发布

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 ObjectMapper?


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'

标签: groovy gretty
1条回答
Animai°情兽
2楼-- · 2019-08-04 10:11

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;
查看更多
登录 后发表回答