Why Does My Groovy Object’s toString Return Empty? A Debugging Tale
The article explains a puzzling bug where a Groovy‑created object's toString becomes empty after fastjson serialization, traces the issue to Java access modifiers, demonstrates the problem with sample code and console output, and resolves it by adding a public modifier.
The author discovered a strange bug while switching from Groovy scripts (which default to public visibility) to Java scripts: an object’s toString appeared empty, and fastjson serialization also produced an empty JSON string.
Reproducing the Issue
public static void main(String[] args) {
Demo demo = new Demo("FunTester", "FunTester");
output(JSON.toJSONString(demo));
testOver();
}
static class Demo {
String name;
String value;
public Demo(String name, String value) {
this.name = name;
this.value = value;
}
}Observed Console Output
INFO-> 当前用户:fv,IP:10.60.192.21,工作目录:/Users/fv/Documents/workspace/fun/,系统编码格式:UTF-8,系统Mac OS X版本:10.15.7
INFO-> {}
Process finished with exit code 0Root Cause Analysis
In Groovy, methods and fields are public by default, so fastjson can access them without issue. When the same class is written in Java, the fields have package‑private visibility unless explicitly declared public, causing fastjson to treat them as inaccessible and output an empty JSON object.
Fix
Adding the public modifier to the class or its fields restores visibility, allowing fastjson to serialize the object correctly. After this change, the JSON output contains the expected values and the toString no longer returns an empty string.
The author chose to continue using Groovy for utility scripts, as it avoids the visibility issue and runs smoothly.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
