【问题标题】:What does `ObjectMapper mapper = []` mean in groovy?`ObjectMapper mapper = []`在groovy中是什么意思?
【发布时间】:2011-10-31 03:03:23
【问题描述】:

我是 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'

【问题讨论】:

    标签: groovy gretty


    【解决方案1】:

    这是对 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;
    

    【讨论】:

    • 谢谢。但是我发现了一些不同的东西:String s = [],那么s就是字符串[]
    • 那是因为字符串是一个特例。 Groovy 只是认为您忘记在 [] 周围加上引号
    • 请查看我更新的问题。有没有文章解释这个功能?
    • 查看我找到的链接。它解释了 Groovy 如何使用列表和映射来调用类的构造函数。
    • 只是为了澄清字符串的情况:Groovy 并不是在“添加引号”——而是 Groovy 在幕后强制对象类型。就像您实际上输入了String s = [] as String,这意味着[].asType(String) 变成了[].toString()。空列表的字符串表示形式为"[]"。 List 和 Map 有一些特殊的asType 处理,以允许它们转换为大多数 GroovyBeans 或 JavaBeans。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-29
    • 1970-01-01
    • 2011-08-12
    • 2017-06-11
    • 2018-03-05
    相关资源
    最近更新 更多