diff --git a/projects/samskivert/src/java/com/samskivert/util/StringUtil.java b/projects/samskivert/src/java/com/samskivert/util/StringUtil.java index ea2dac03..39f39e94 100644 --- a/projects/samskivert/src/java/com/samskivert/util/StringUtil.java +++ b/projects/samskivert/src/java/com/samskivert/util/StringUtil.java @@ -1,5 +1,5 @@ // -// $Id: StringUtil.java,v 1.20 2002/01/30 18:21:14 mdb Exp $ +// $Id: StringUtil.java,v 1.21 2002/02/02 00:03:14 mdb Exp $ // // samskivert library - useful routines for java programs // Copyright (C) 2001 Michael Bayne @@ -24,6 +24,9 @@ import java.awt.geom.Dimension2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; + import java.util.Enumeration; import java.util.Iterator; import java.util.StringTokenizer; @@ -259,6 +262,42 @@ public class StringUtil } } + /** + * Generates a string representation of the supplied object by calling + * {@link #toString} on the contents of its public fields and + * prefixing that by the name of the fields. For example: + * + *

[itemId=25, itemName=Elvis, itemCoords=(14, 25)] + */ + public static String fieldsToString (Object object) + { + StringBuffer buf = new StringBuffer("["); + Class clazz = object.getClass(); + Field[] fields = clazz.getFields(); + + // we only want non-static, non-final, non-transient fields + for (int i = 0; i < fields.length; i++) { + int mods = fields[i].getModifiers(); + if ((mods & Modifier.PUBLIC) == 0 || + (mods & Modifier.STATIC) != 0) { + continue; + } + + if (buf.length() > 1) { + buf.append(", "); + } + + buf.append(fields[i].getName()).append("="); + try { + toString(buf, fields[i].get(object)); + } catch (Exception e) { + buf.append(""); + } + } + + return buf.append("]").toString(); + } + /** * Generates a string from the supplied bytes that is the HEX encoded * representation of those bytes.