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:

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:

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.

2 replies
  1. virtualeyes
    virtualeyes says:

    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

Comments are closed.