2

我写了一个小 Groovy 脚本,它暴露了一个非常奇怪的行为。谁能解释一下?

// 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)
4

1 回答 1

4

The problem is that:

map["metaClass"]="c"

is the same as writing:

map.metaClass = "c"

I am guessing that before it delegates to the Map.put(x,y) method, it checks to see if a setXxxx method exists on the object.

As there is a method (in every object in Groovy) called setMetaClass(), it then calls this method instead of setting the property in the map (and fails to cast "c" to a metaClass object, as you have seen)

Workarounds:

  • Don't have a key called metaClass
  • Use map.put( 'metaClass', 'c' ) instead of the groovy magic
于 2010-10-19T09:57:31.897 回答