commons-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Gary Gregory <ggreg...@seagullsw.com>
Subject RE: [lang] ToStringBuilder.reflectionToString
Date Wed, 16 Jul 2003 17:59:29 GMT
Here is one option below. Supporting formatting in ToStringStyle would be
better of course. We can think about it for post 2.0 (or now).

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.builder.ReflectionToStringBuilder;

/**
 * @author <a href="mailto:ggregory@seagullsw.com">Gary Gregory</a>
 * @version $Id: $
 */
public class TestRTSB {

    private Date myDate = new Date();
    private int foo= 22;

    public static void main(String[] arguments) {
        System.out.println(new TestRTSB());
    }

    public String toString() {
        return (new ReflectionToStringBuilder(this) {
            protected Object getValue(Field field) throws
IllegalArgumentException, IllegalAccessException {
                Object value = super.getValue(field);
                if ("myDate".equals(field.getName())) {
                    return new SimpleDateFormat("yyyy-MM-dd").format(value);
                } else {
                    return value;
                }
            }
        }).toString();
    }
}

-----Original Message-----
From: Brian Buckley [mailto:briankbuckley@comcast.net] 
Sent: Wednesday, July 16, 2003 08:55
To: commons-user@jakarta.apache.org
Subject: [lang] ToStringBuilder.reflectionToString 

Hello,

Is there a good way to customize ToStringBuilder.reflectionToString to
output a customized format based on the type of field?

For example, if a class contains a field of type java.util.Date, how can one
make ToStringBuilder.reflectionToString use a custom SimpleDateFormatter on
the field instead of Date's toString()?

[java.text.SimpleDateFormat("yyyy-MM-dd").format(myField) instead of
myField.toString();]

I saw some customization options in ToStringStyle but did not see an option
to customize formatting by type of field.  Is this possible?  Any tips
appreciated.  Thanks.

Brian




---------------------------------------------------------------------
To unsubscribe, e-mail: commons-user-unsubscribe@jakarta.apache.org
For additional commands, e-mail: commons-user-help@jakarta.apache.org

Mime
  • Unnamed multipart/alternative (inline, None, 0 bytes)
View raw message