views:

123

answers:

1

In the following Groovy snippet, I attempt to replace both the hashCode and toString methods

String.metaClass.toString = {-> "override" }
String.metaClass.hashCode = {-> 22 }

But when I test it out, only the replacement of hashCode works

String s = "foo"
println s.hashCode()  // prints 22
println s.toString()  // prints "foo"

Is toString somehow a special case (possibly for security reasons)?

+3  A: 

See the first comment on this issue. It says about String's toString and other String related classes:

(...) seems to be intent, it is probably a good idea to have a faster invocation for classes that don't allow overriding toString().

Felipe Cypriano
How do you know which are the "classes that don't allow overriding toString()"?
Don
I posted a new issue which hopefully should clear things up... http://jira.codehaus.org/browse/GROOVY-4210
tim_yates
Thanks Tim, so I guess the short answer is "it's a bug"?
Don