集册 Java实例教程 打印给定bean的所有属性。

打印给定bean的所有属性。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

630
打印给定bean的所有属性。
//N o w J a v a . c o m 提 供


//package com.nowjava;

import java.beans.BeanInfo;

import java.beans.Introspector;

import java.beans.PropertyDescriptor;


public class Main {



    /**

     * 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 {/** 来自 时代Java公众号**/

            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)

     
展开阅读全文