Java奇技淫巧:获取一个类的所有字段

luckyFang 2021年02月06日 170次浏览

没啥好说的就是纯反射,上才艺

package com.lu.spring5.Utils;

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author luckyFang
 * @date 2021/2/6 17:50
 * @file Util.java
 * @desc
 */

public class Util {

    /**
     * 打印分割线
     * @param count
     */
    public static void printSplitLine(int count) {
        printSplitLine("*", count);
    }

    // 打印分割线
    public static void printSplitLine(String split, int count) {
        printSplitLine(split, count, null);
    }

    public static void printSplitLine(String split, int count, String head) {
        int pos = 0;
        // default value
        if (head != null) pos = count / 2;
        else head = "";
        for (int i = 0; i < count; i++) {
            if (i == pos) System.out.print(head);
            System.out.print(split);
        }
        System.out.println();
    }

    /**
     *  通过反射 获取字段 并显示
     * @param o
     * @param <T>
     * @return
     * @throws IllegalAccessException
     */
    public static <T> Map<String, Object> printAllFields(T o) throws IllegalAccessException {
        Map<String, Object> container = new HashMap<>();
        Class<?> c = o.getClass();
        Field[] fields = c.getDeclaredFields();
        printSplitLine("=", 20, "字段列表");
        String line = "";
        for (Field field : fields) {
            if (field.getName().startsWith("$")) continue;
            field.setAccessible(true);
            // 如果是数组则进行处理
            if (field.get(o).getClass().isArray()){
                try {
                    line = field.getName() + "=" + arrayToString(field.get(o));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else{
                line = field.getName() + "=" + field.get(o).toString();
            }
            System.out.println(line);
            container.put(field.getName(), field.get(o));
        }
        printSplitLine("=", 26);
        return container;
    }

    public static String arrayToString(Object arr) throws Exception {
        if (!arr.getClass().isArray()) throw new Exception("不是数组类型");
        // 转化为String 类型 方便处理
        int length = Array.getLength(arr);
        String[] objects = new String[length];
        for (int i = 0; i < length; i++) objects[i]=Array.get(arr,i).toString();
        return Arrays.stream(objects).collect(Collectors.toList()).toString();
    }


}

使用方法

  public class Inner{
        private final String a ="Hello";
        private final int b =20;
        private final double c =3.14;
        private final int[] d =new int[]{1,3,5,7,9};
        private List<String> e = new ArrayList<>();
        private Map<String,String> f = new HashMap<>();
        private Set<Integer> g =new HashSet<>();

        public Inner() {
            e.add("world");
            e.add("test");
            f.put("A","B");
            f.put("C","D");
            g.add(5);
            g.add(6);
        }

        public static void main(String[] args) throws IllegalAccessException {
            Util.printAllFields(new Inner());
        }
    }

运行结果

==========字段列表==========
a=Hello
b=20
c=3.14
d=[1, 3, 5, 7, 9]
e=[world, test]
f={A=B, C=D}
g=[5, 6]
==========================