Groovy Script setLength Error with StringBuilder and How to Work Around It
The article describes a Groovy scripting issue where calling StringBuilder.setLength(0) triggers a NoSuchMethodError, explains Groovy's automatic property generation, demonstrates debugging steps, metaprogramming attempts, and the final workaround that resolves the error.
While writing a Groovy script I encountered a strange error: calling sb.setLength(0) on a StringBuilder caused a No signature of method: java.lang.StringBuilder.setLength() error.
Groovy automatically creates a property for getter/setter pairs, so a method named getFun() / setFun() would generate a fun property, and vice‑versa; this flexibility can hide missing methods.
Original code that triggered the error:
StringBuilder sb = new StringBuilder() for (int i = 0; i < 3; i++) { sb.append("a" + i) output(sb.toString()) sb.setLength(0) }
The Java AbstractStringBuilder#setLength(int newLength) method either truncates the string when newLength is smaller than the current length or pads it with null characters when larger.
The exact error message was:
No signature of method: java.lang.StringBuilder.setLength() is applicable for argument types: (Integer) values: [0] at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:70) ...
Because Groovy treats StringBuilder differently, the call was resolved as a property access rather than a method call, and the integer argument was seen as an Integer instead of the expected int , leading to the failure.
To test the hypothesis, I added a meta‑class property:
StringBuilder.metaClass.length = 32 StringBuilder sb = new StringBuilder() for (int i = 0; i < 3; i++) { sb.append("a" + i) output(sb.toString()) sb.setLength(0) }
This removed the error but also disabled the actual setLength functionality because the property took precedence over the method.
Finally, I removed the setLength call entirely:
StringBuilder.metaClass.length = 32 StringBuilder sb = new StringBuilder() for (int i = 0; i < 3; i++) { sb.append("a" + i) output(sb.toString()) }
That solved the problem in the current project, but the issue could not be reproduced in another Maven/Gradle project. Updating the Groovy dependency and the compilation plugin version eliminated the bug, suggesting it was a version‑specific Groovy compilation quirk.
FunTester
10k followers, 1k articles | completely useless
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.