Explain Codes LogoExplain Codes Logo

How do I print my Java object without getting "SomeType@2f92e0f4"?

java
reflection
tostring
debugging
Nikita BarsukovbyNikita Barsukov·Oct 21, 2024
TLDR

To customize the output of your Java object, override the toString() method in your class like so:

public class MyObject { private int id; private String name; // Constructor... Ain't he a good guy? public MyObject(int id, String name) { this.id = id; this.name = name; } // Custom toString() implementation, 'cause we don't like generic stuff, right? @Override public String toString() { return String.format("MyObject{id=%d, name='%s'}", id, name); } } // Usage MyObject obj = new MyObject(1, "JavaBean"); System.out.println(obj); // Prints: MyObject{id=1, name='JavaBean'}

Advanced strategies with toString()

Libraries to the rescue

Ever heard of ReflectionToStringBuilder from Apache Commons Lang library? It's a detailed string representation of the object's state, ideal for debugging and logging:

import org.apache.commons.lang3.builder.ReflectionToStringBuilder; // Using ReflectionToStringBuilder, or as I like to call it, the "tell me what you got" builder System.out.println(ReflectionToStringBuilder.toString(obj));

When dealing with array objects, Arrays.toString() and Arrays.deepToString() are life-savers. It's like a toString() for arrays without the fuss!

import java.util.Arrays; int[] array = {1, 2, 3}; // Array's first day at school picture - a single-dimensional array System.out.println(Arrays.toString(array)); // [1, 2, 3] int[][] matrix = {{1, 2}, {3, 4}}; // Now we're getting deep, it's inception time with a multi-dimensional array System.out.println(Arrays.deepToString(matrix)); // [[1, 2], [3, 4]]

Wise use of IDEs

Modern IDEs such as IntelliJ IDEA and Eclipse have automated toString() generation. It's like having a personal assistant to write boring toString() methods.

JSON beauty with Gson

For converting Java objects to JSON strings, Gson's pretty printing makes it look like poetry:

import com.google.gson.GsonBuilder; // Gson, turning your plain old Java object into a beautiful JSON-string supermodel String json = new GsonBuilder().setPrettyPrinting().create().toJson(obj); System.out.println(json);

Ultimate toString tips

Performance boost with StringBuilder

For large objects or in heavy loops, a StringBuilder in your toString() is like putting a Tesla engine in your car:

@Override public String toString() { // And they said Rome wasn't built in a day... StringBuilder sb = new StringBuilder("MyObject{"); sb.append("id=").append(id); sb.append(", name='").append(name).append('\''); sb.append('}'); return sb.toString(); }

Handling nulls

Prevent NullPointerException by treating potential null values like polite guests:

public String toString() { // Handle null name like a secret agent undercover as "Nameless" return String.format("MyObject{id=%d, name='%s'}", id, Objects.toString(name, "Nameless")); }

Collections and toString()

In classes like List, Set, or Map, ensure that each element's toString() is like an Oscar-winning actor, so your collection is nothing less than a star-studded movie.

Tricky situations and how to handle them

  • Circular references: Prioritize your sanity over endless loops. Break circular dependencies in toString().
  • Sensitive data: Passwords in toString()? Nope. Exclude sensitive fields or use text replacement techniques.
  • Performance: Cache your toString() result if it's called repeatedly and tends to stay the same. It's like saving your favorite pizza place as a speed dial.