Print all properties for a given bean. - Java Reflection

Java examples for Reflection:Java Bean

Description

Print all properties for a given bean.

Demo Code


//package com.java2s;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;

public class Main {


    /**/*from w  ww.j  a v a 2 s.c  o m*/
     * Print all properties for a given bean. It's useful for overwriting toString method.
     * 
     * @param bean Object to get all properties from.
     * @param showNulls Determine if you wether you want to show null properties or not.
     * @return String representing bean state.
     * @author andres santana
     */
    public static String toStringBean(Object bean, boolean showNulls) {
        if (bean == null)
            return null;
        StringBuilder sb = new StringBuilder(bean.getClass().getName())
                .append("[");
        // new ToStringCreator(this)
        try {
            BeanInfo bi = Introspector.getBeanInfo(bean.getClass());
            PropertyDescriptor[] pd = bi.getPropertyDescriptors();
            for (int i = 0; i < pd.length; i++) {
                if (!"class".equals(pd[i].getName())) {
                    Object result = pd[i].getReadMethod().invoke(bean);
                    if (showNulls || result != null) {
                        sb.append(pd[i].getDisplayName()).append("=")
                                .append(result);
                        if (i == pd.length - 1)
                            continue;
                        sb.append(",");
                    }
                }
            }
        } catch (Exception ex) {
        }

        return sb.append("]").toString();
    }
}

Related Tutorials