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.



  1. You should try and see if ExpandoMetaClass.enableGlobally() works in your case.

    Comment by geo — October 22, 2009 @ 3:42 pm

    • That was the first thing I tried, does not help though.

      Comment by omgo — October 22, 2009 @ 4:14 pm

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at

%d bloggers like this: