객체로부터 반사를 사용하여 필드 인쇄

3331 단어
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 = "java2s.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) {
            sb.append(o);
            return;
        }
        if (o instanceof Object[]) {
            Object[] os = (Object[]) o;
            sb.append("(").append(os.length).append(")[
"); int i = 0; for (Object o2 : os) { generateIndentation(sb, indentation); sb.append(i++); sb.append(" => "); printFields(o2, sb, indentation + 2); sb.append("
"); } 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(")[
"); int i = 0; for (Object o2 : os) { generateIndentation(sb, indentation); sb.append(i++); sb.append(" => "); printFields(o2, sb, indentation + 2); sb.append("
"); } 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("{
"); 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("
"); } catch (Exception e) { } } int i = sb.length() - 2; if (sb.charAt(i) == '{') sb.setCharAt(i + 1, '}'); else { generateIndentation(sb, indentation - 2); sb.append("}"); } } private static final void generateIndentation(StringBuilder sb, int indentation) { while ((indentation = indentation - 2) >= 0) { sb.append(" "); } } }

좋은 웹페이지 즐겨찾기