Tutorials : Save Time with the Ultimate toString Method :

Save Time with the Ultimate toString Method

by Keld H. Hansen

Every Java class has a toString() method that gives a string representation of the object. If a class does not implement its own version of toString, it will be inherited from java.lang.Object. During the development and debugging of a Java application, it's really useful to work with classes that have toString methods, which return detailed and understandable information about a class. However, many developers don't take the time to code many of these methods, probably because it's either too trivial or too complicated to code them. Also, other tasks in the development process may seem like a higher priority.

But coding toString methods doesn't have to be an ordeal; this article shows you how to make a generic toString method that can be used for any class.

Step #1: Introspection

To make a generic toString method, you first need to be able to find all the properties of an object—both the member variables as well as the static variables. This takes only a few lines of code:
Object obj  = ...
Class clazz = obj.getClass();
Field[] fields = clazz.getDeclaredFields();
Field is part of the java.lang.reflect package that provides information about classes and objects. The Field class gives access to the names, types, and values of the variables (fields) in a class. The following code snippet prints out data for the all fields in a class:
for (int i = 0; i < fields.length; i++) {
  Field f = fields[i];
  System.out.println(f.getName() + " is of type " + f.getType() + 
                                   " and has value=" + f.get(obj));
}

The following example of a class contains fields of different types and complexity:
public class Reflection1 {

public int i           = 13;
public static int j    = 909;
public String s        = "Hello World";
public Serializable synch;
public int[] iArray    = {1,2,3};
public String[] sArray = {"abc", "def"};
public Collection coll = Arrays.asList(sArray);
public Map map         = new HashMap();
public File file       = new File("my.file");
public Logger logger   = Logger.getLogger("myLogger");

public Reflection1() {
  map.put("Key1", "Value1");
  map.put("Key2", "Value2");
}

public static void main(String[] args) throws Exception {
  Object obj = new Reflection1();
  Class clazz = obj.getClass();
  Field[] fields = clazz.getDeclaredFields();
  // For each field:
  for (int i = 0; i < fields.length; i++) {
    Field f = fields[i];
    System.out.println(f.getName() + " is of type " + f.getType() +
                                     " and has value=" + f.get(obj));
  }
}

}
When the program is run, you get this output:
i is of type int and has value=13
j is of type int and has value=909
s is of type class java.lang.String and has value=Hello World
synch is of type interface java.io.Serializable and has value=null
iArray is of type class [I and has value=[I@1f6a7b9
sArray is of type class [Ljava.lang.String; and 
   has value=[Ljava.lang.String;@7d772e
coll is of type interface java.util.Collection and has value=[abc, def]
map is of type interface java.util.Map and 
   has value={Key1=Value1, Key2=Value2}
file is of type class java.io.File and has value=my.file
logger is of type class java.util.logging.Logger and 
   has value=java.util.logging.Logger@11b86e7
All fields are found, and most of the values look fine, except for:
  • Arrays
  • The Logger class, which probably has a complex structure
Except for null values, the values printed are simply obtained by f.get(obj).toString(), and this method call has very different implementations. You may recall that the default implementation of toString, inherited from the Object class, is simply:
    getClass().getName() + '@' + Integer.toHexString(hashCode())
In the output above, a couple of strings have this same format. But note that the Collection and Map interfaces actually print very nicely!

One thing is worth noting: even for the primitive types (fields i and j in the example above), f.get() returns an object. For these types, the JDK's wrapper classes (Integer, Float, etc.) are used by the reflection API.

Before continuing, there are two things you'll need to add. First, the code above will only print the fields that are "visible". Therefore, private fields will not be listed unless you add this line:

Field[] fields = clazz.getDeclaredFields();
AccessibleObject.setAccessible(fields, true);
Second, if the object whose fields you want to list extends another class and you also want to list the fields of the superclass, you need to add a loop through the superclasses:
do {
  Field[] fields = clazz.getDeclaredFields();
  AccessibleObject.setAccessible(fields, true);
  // For each field:
  for (int i = 0; i < fields.length; i++) {
    Field f = fields[i];
    System.out.println(f.getName() + " is of type " + f.getType() + 
                                     " and has value=" + f.get(obj));
  }
  clazz = clazz.getSuperclass();
} while (clazz != null && clazz != Object.class);

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.