GStringImpl cannot be cast to java.lang.String

Last week, we got a nasty error in our application:

java.lang.ClassCastException: org.codehaus.groovy.runtime.GStringImpl cannot be cast to java.lang.String

The stacktrace was not helpful at all, and showed that the error was caused by a NullPointerException in Melody, which was a false message. After some searching around, we found the following code to be the culprit:

render(view: 'index', model: ["${command.class.simpleName}": command)

What happens here, is that a GString is used as a map key for rendering the model in the view. It’s never a good idea to use GStrings as a Map key, since the hashCode of GStrings are not guaranteed to be stable. A better approach is to use a String instead, which can be done using the following code:

render(view: 'index', model: [(command.class.simpleName): command)

The above is our current fix, and we changed our CodeNarc GString as Map key to a prio 1 rule. Whenever a prio 1 error occurs, our build will fail, preventing future errors like this.

Erik Pragt
Erik Pragt
Erik Pragt is a passionate software developer with a broad range of experience in both static dynamic (Java, Scala) languages. Having worked as a consultant for a broad range of customers mostly in the Telecom, ISP, and banking sector, Erik is now an independent freelance consultant. In the limited time he's not sitting behind the computer he can be found in the gym, riding his motorcycle or diving, always looking for new inspiration.
Recent Posts
Showing 2 comments
  • virtualeyes

    Fabulous find Erik, thanks.

    Truly useless stacktrace as far as quickly pinning down the error, although better than MME at line -1 of unknown class.

pingbacks / trackbacks

Start typing and press Enter to search