Assists in implementing {@link Object#toString()} methods using reflection.
This class uses reflection to determine the fields to append. Because these fields are usually private, the class uses {@link java.lang.reflect.AccessibleObject#setAccessible(java.lang.reflect.AccessibleObject[],boolean)} tochange the visibility of the fields. This will fail under a security manager, unless the appropriate permissions are set up correctly.
A typical invocation for this method would look like:
public String toString() { return ReflectionToStringBuilder.toString(this); }
You can also use the builder to debug 3rd party objects:
System.out.println("An object: " + ReflectionToStringBuilder.toString(anObject));
A subclass can control field output by overriding the methods:
- {@link #accept(java.lang.reflect.Field)}
- {@link #getValue(java.lang.reflect.Field)}
For example, this method does not include the password
field in the returned String
:
public String toString() { return (new ReflectionToStringBuilder(this) { protected boolean accept(Field f) { return super.accept(f) && !f.getName().equals("password"); } }).toString(); }
The exact format of the toString
is determined by the {@link ToStringStyle} passed into theconstructor.
@author Apache Software Foundation
@author Gary Gregory
@author Pete Gieser
@since 2.0
@version $Id: ReflectionToStringBuilder.java 889215 2009-12-10 11:56:38Z bayard $