1. 程式人生 > >學習筆記 利用反射 手寫一個簡單的實體類 轉json 的方法

學習筆記 利用反射 手寫一個簡單的實體類 轉json 的方法

不得不說 反射真的是個好動 

# 貼上我的程式碼  

package com.lengff.test;


import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


public class toJsonUtil {

    public static void main(String[] args) {
        Person test = new Person("test", 123);
        String json = toJSONString(test);
        System.out.println(json);
    }


    /**
     * 將實體類轉成json 字串
     *
     * @param bean
     * @return
     */
    public static String toJSONString(Object bean) {
        Class<?> clazz = bean.getClass();
        //獲取所有欄位名
        Field[] fields = clazz.getDeclaredFields();
        String json = "";
        if (fields.length > 0) {
            json += "{";
            int size = 0;
            for (Field field : fields) {
                size++;
                String name = field.getName();
                Method method = null;
                Object invoke = null;
                try {
                    //根據欄位名首字母大寫 拼接獲取方法
                    method = clazz.getMethod("get" + name.substring(0, 1).toUpperCase() + name.substring(1), null);
                    //執行get 方法 獲取欄位對應的值
                    invoke = method.invoke(bean, null);
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
                //拼接成json 格式的字串
                if (size < fields.length) {
                    json += "'" + name + "':'" + invoke.toString() + "',";
                } else {
                    json += "'" + name + "':'" + invoke.toString() + "'";
                }
            }
            json += "}";
        }
        return json;
    }

}

/**
 * 實體 bean
 */
class Person {
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

#原理:

就是利用反射,根據獲取實體類裡面的所有欄位名,再根據欄位名獲取該欄位名的get 方法,從而執行get 方法 ,拿到欄位裡的值,再用字串拼接形成我們需要的json格式字串

#說明:

由於寫的很簡單,適用的場景很低,只能適用一般的實體類,稍微高階一點的估計都不行,就只是一個學習的筆記,更好的去理解和學習反射