欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > > 文章正文

重写Bean的toString()方法,beantostring

来源: javaer 分享于  点击 16814 次 点评:161

重写Bean的toString()方法,beantostring


    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");

        // 获取Bean的所有方法
        Method[] methods = this.getClass().getMethods();

        // 方法名
        String methodName = null;
        String fieldName = null;

        try {
           
            // 遍历,取Getter方法
            for (Method method : methods) {
                methodName = method.getName();

                if (methodName.startsWith("get")) {

                    if ("getClass".equals(methodName)) {
                        continue;
                    }

                    fieldName = methodName.substring(3);
                    fieldName = fieldName.substring(0, 1).toLowerCase()
                            + fieldName.substring(1);
                   
                    sb.append(fieldName + "=[" + method.invoke(this, null) + "] ");
                }
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

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

相关文章

    暂无相关文章

用户点评