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

半腔热情 提交于 2019-12-24 08:04:42

问题


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'

回答1:


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;


来源:https://stackoverflow.com/questions/7130548/what-does-objectmapper-mapper-mean-in-groovy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!