代码之家  ›  专栏  ›  技术社区  ›  Riduidel

将一个名为metaClass的键放入映射中

  •  2
  • Riduidel  · 技术社区  · 14 年前

    small Groovy script 这暴露了一种非常怪异的行为。有人能解释一下吗?

    // Creating a groovy map 
    def map = [:] 
    // Putting a value in 
    map["a"]="b"
    // Render it without trouble 
    println map["a"] 
    // Putting another value in (yup, this one has THE name) 
    map["metaClass"]="c"
    // Failing to render it 
    println map["metaClass"]
    

    org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'c' with class 'java.lang.String' to class 'groovy.lang.MetaClass'
    at Script1.run(Script1.groovy:8)
    
    1 回复  |  直到 14 年前
        1
  •  4
  •   tim_yates    14 年前

    问题是:

    map["metaClass"]="c"
    

    map.metaClass = "c"
    

    我猜在它代表 Map.put(x,y) 方法,它检查是否 setXxxx 对象上存在方法。

    setMetaClass() ,然后调用此方法,而不是在映射中设置属性(并且无法强制转换 "c" 对于元类对象,如您所见)

    解决方法:

    • 没有叫的钥匙 metaClass
    • 使用 map.put( 'metaClass', 'c' ) 而不是一般的魔术