集册 Java实例教程 通过反射从对象打印字段

通过反射从对象打印字段

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

505
通过反射从对象打印字段

//package com.nowjava;
/* from 
时代Java - N o w  J a v a . c o m*/

import java.lang.reflect.Field;

import java.lang.reflect.Modifier;

import java.util.Collection;


public class Main {

    public static void main(String[] argv) {

        Object o = "nowjava.com";

        StringBuilder sb = new StringBuilder();

        int indentation = 42;

        printFields(o, sb, indentation);

    }


    private static final void printFields(Object o, StringBuilder sb,

            int indentation) {

        if (o == null) {

            sb.append("null");

            return;

        }

        if (indentation > 12) {
        /**
         from
        * 时 代 J a v a 公 众 号 
        **/

            sb.append(o);

            return;

        }

        if (o instanceof Object[]) {

            Object[] os = (Object[]) o;

            sb.append("(").append(os.length).append(")[\n");

            int i = 0;

            for (Object o2 : os) {

                generateIndentation(sb, indentation);

                sb.append(i++);

                sb.append(" => ");

                printFields(o2, sb, indentation + 2);

                sb.append("\n");

            }

            i = sb.length() - 1;

            if (os.length == 0)

                sb.setCharAt(i, ']');

            else {

                generateIndentation(sb, indentation - 2);

                sb.append(']');

            }

            return;

        }

        if (o instanceof Collection<?>) {

            Collection<? extends Object> os = (Collection<?>) o;

            sb.append("(").append(os.size()).append(")[\n");

            int i = 0;

            for (Object o2 : os) {

                generateIndentation(sb, indentation);

                sb.append(i++);

                sb.append(" => ");

                printFields(o2, sb, indentation + 2);

                sb.append("\n");

            }

            i = sb.length() - 1;

            if (os.size() == 0)

                sb.setCharAt(i, ']');

            else {

                generateIndentation(sb, indentation - 2);

                sb.append(']');

            }

            return;

        }

        if (o.getClass().getName().startsWith("java")

                && !o.getClass().getName().equals("java.lang.Object")) {

            sb.append(o);

            return;

        }

        sb.append("{\n");

        for (Field f : o.getClass().getDeclaredFields()) {

            f.setAccessible(true);

            if (f.isSynthetic() || (f.getModifiers() & Modifier.STATIC) > 0)

                continue;

            try {

                generateIndentation(sb, indentation);

                sb.append(f.getName()).append("=");

                printFields(f.get(o), sb, indentation + 2);

                sb.append("\n");

            } catch (
展开阅读全文