Omgo's Blog

October 21, 2009

Expandometaclass gotcha

Filed under: Groovy — aswin @ 9:10 pm

I hit a gotcha while trying out some basic Meta stuff in groovy. Say you wanted to replace the default “toString()” method of your String class with the following groovy code

String.metaClass.toString = {"completely useless"}
println new String("world saver").toString()

I was expecting to see the “completely useless” as answer, but turns out that the toString() method did not get overridden. After spending some time analyzing what was going on looks like the method being used for the invocation is actually the one from the super interface of String , CharSequence. This handle is used by the metaclass system and it resolves to the actual toString method implemented in the String class itself , completely ignoring the metaclass version we added. So what needs to be done to get the effect is to rewrite the code to look like

CharSequence.metaClass.toString = {"completely useless"}
println new String("world saver").toString()

and you get “completely useless”.  This is not exactly what one would want,  as this would affect all the subclasses that has implemented this method and all of them would return “completly useless” when their toString() method is invoked.   In short if you have a superinterface method you are trying to override (or replace I must say) using ExpandoMetaclass facility , the chances are that it would have this issue, so plan ahead 😉

ExpandoMetaClass and Metaclass system itself is getting rewritten for the Groovy 2 release I guess, so hopefully these kind of issues would go away.

Advertisements

Blog at WordPress.com.