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.

1 Comment

  1. 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.

Trackbacks/Pingbacks

  1. An Army of Solipsists » Blog Archive » This Week in Grails (2011-35) - [...] GStringImpl cannot be cast to java.lang.String [...]

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>