Java toString() using reflection? Java toString() using reflection? java java

Java toString() using reflection?


Apache commons-lang ReflectionToStringBuilder does this for you.

import org.apache.commons.lang3.builder.ReflectionToStringBuilder// your code goes herepublic String toString() {   return ReflectionToStringBuilder.toString(this);}


Another option, if you are ok with JSON, is Google's GSON library.

public String toString() {    return new GsonBuilder().setPrettyPrinting().create().toJson(this);}

It's going to do the reflection for you. This produces a nice, easy to read JSON file. Easy-to-read being relative, non tech folks might find the JSON intimidating.

You could make the GSONBuilder a member variable too, if you don't want to new it up every time.

If you have data that can't be printed (like a stream) or data you just don't want to print, you can just add @Expose tags to the attributes you want to print and then use the following line.

 new GsonBuilder().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().create().toJson(this);


W/reflection, as I hadn't been aware of the apache library:

(be aware that if you do this you'll probably need to deal with subobjects and make sure they print properly - in particular, arrays won't show you anything useful)

@Overridepublic String toString(){    StringBuilder b = new StringBuilder("[");    for (Field f : getClass().getFields())    {        if (!isStaticField(f))        {            try            {                b.append(f.getName() + "=" + f.get(this) + " ");            } catch (IllegalAccessException e)            {                // pass, don't print            }        }    }    b.append(']');    return b.toString();}private boolean isStaticField(Field f){    return Modifier.isStatic(f.getModifiers());}