Wednesday, 12 January 2011

Printing the Objects which has no toString method using Reflection

once you want to use toString method in your classes, you will quickly see that all Object without defined toString method, will just showed by their memory address.
Although you can walk through your classes and add a proper toString method to each of them, you will be stopped once you use a thirdparty or generated object.
I will show you here how you can simply printout your object none less. this method uses Reflection to iterate through attributes of a class and prints out its value.
I found later, using ReflectionToStringBuilder is more comfortable to write my own.
so here is the solution:

first write a class which extends ToStringStyle to customize appearance of fields (e.g. use Tabs, how to printout Array and so on)



public class PrintObjectStyle extends ToStringStyle {
    private final static ToStringStyle instance = new PrintObjectStyle();

    public PrintObjectStyle() {
        setArrayContentDetail(true);
        setUseShortClassName(true);
        setUseClassName(true);
        setUseIdentityHashCode(false);
        setArrayStart("\n\t{");
        setArrayEnd("\n\t}");
        setArraySeparator("\n\t");
        setFieldSeparator(", " + SystemUtils.LINE_SEPARATOR + "  ");
    }

    public static ToStringStyle getInstance() {
        return instance;
    }

    ;

    @Override
    public void appendDetail(StringBuffer buffer, String fieldName, Object value) {
        if (!value.getClass().getName().startsWith("java")) {
            buffer.append(ReflectionToStringBuilder.toString(value, instance));
        }
        else {
            super.appendDetail(buffer, fieldName, value);
        }
    }

    @Override
    public void appendDetail(StringBuffer buffer, String fieldName, Collection value) {
        appendDetail(buffer, fieldName, value.toArray());
    }
}



now you can call this line everywhere that you want to printout an Object.



System.out.println(ReflectionToStringBuilder.toString(myObject, PrintObjectStyle.getInstance()));


No comments:

Post a Comment