Java - Write code to output field value via reflection

Requirements

Write code to output field value via reflection

Read the value from an Object passed in.

Hint

Get all fields from the Class

Append field name and value to a StringBuffer.

Demo

import java.lang.reflect.Field;
import java.util.Date;
import org.apache.log4j.Logger;

public class Main{
    public static void main(String[] argv){
        Object o = "book2s.com";
        System.out.println(toString(o));
    }//from w  w w  .java  2  s.c o m
    public static String toString(Object o) {
        StringBuffer sb = new StringBuffer();
        if (null != o) {
            Class<?> clz = o.getClass();
            Field[] fields = clz.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                try {
                    sb.append(field.getName() + ":" + field.get(o) + ";");
                } catch (IllegalArgumentException e) {

                    e.printStackTrace();
                } catch (IllegalAccessException e) {

                    e.printStackTrace();
                }
            }

        }
        return sb.toString();
    }
}