集册 Java实例教程 通过反射作为字符串从对象获取所有字段

通过反射作为字符串从对象获取所有字段

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

424
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
通过反射作为字符串从对象获取所有字段


//package com.nowjava;
//时 代 J a v a 提供

public class Main {

    public static void main(String[] argv) throws Exception {

        Object obj = "nowjava.com";

        System.out.println(getAllFieldsAsString(obj));

    }


    public static String getAllFieldsAsString(final Object obj) {

        final StringBuilder sb = new StringBuilder();

        writeAllFieldsToBuffer(obj, sb);


        return sb.toString();

    }


    public static void writeAllFieldsToBuffer(final Object obj,

            final StringBuilder out) {// from 时 代 J a v a 公 众 号 - nowjava.com

        final Class<?> thisClass = obj.getClass();


        for (final java.lang.reflect.Field f : thisClass.getFields()) {

            try {

                out.append(f.getName() + " = ");

                final Class<?> fType = f.getType();


                if (fType.isPrimitive()) {

                    final String n = fType.getName();

                    if (n.equals("boolean")) {

                        out.append(f.getBoolean(obj) + "\n");

                    } else if (n.equals("byte")) {

                        out.append(f.getByte(obj) + "\n");

                    } else if (n.equals("char")) {

                        out.append(f.getChar(obj) + "\n");

                    } else if (n.equals("double")) {

                        out.append(f.getDouble(obj) + "\n");

                    } else if (n.equals("float")) {

                        out.append(f.getFloat(obj) + "\n");

                    } else if (n.equals("int")) {

                        out.append(f.getInt(obj) + "\n");

                    } else if (n.equals("long")) {

                        out.append(f.getLong(obj) + "\n");

                    } else if (n.equals("short")) {

                        out.append(f.getShort(obj) + "\n");

                    } else {

                        throw new IllegalStateException(

                                "unknown primitive type: "

                   
展开阅读全文