Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You could do:</p> <pre><code>@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getName()); sb.append(": "); for (Field f : getClass().getDeclaredFields()) { sb.append(f.getName()); sb.append("="); sb.append(f.get(this)); sb.append(", "); } return sb.toString(); } </code></pre> <p><em>Don't</em> use string concatenation to construct an end result from 15 data members, particularly if the <code>toString()</code> will be called a lot. The memory fragmentation and overhead could be really high. Use <code>StringBuilder</code> for constructing large dynamic strings.</p> <p>I usually get my IDE (IntelliJ) to simply generate <code>toString()</code> methods for me rather than using reflection for this.</p> <p>Another interesting approach is to use the <a href="http://projectlombok.org/features/ToString.html" rel="noreferrer">@ToString annotation from Project Lombok</a>:</p> <blockquote> <pre><code>import lombok.ToString; @ToString(excludes="id") public class ToStringExample { private static final int STATIC_VAR = 10; private String name; private Shape shape = new Square(5, 10); private String[] tags; private int id; @ToString(callSuper=true, includeFieldNames=true) public static class Square extends Shape { private final int width, height; public Square(int width, int height) { this.width = width; this.height = height; } } } </code></pre> </blockquote> <p>I find this much more preferable to, say, Jakarta Commons toString builders because this approach is far more configurable and it's also built at compile-time not run-time.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload