Put a key named metaClass in a Map
I've written a small Groovy script that exposes a very weird behaviour. can anyone explain it ?
// 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"]
My question in that case is quite simple : why does the last instruction will throw the exception below :
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)
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
精彩评论