学习笔记 利用反射 手写一个简单的实体类 转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格式字符串

#说明:

由于写的很简单,适用的场景很低,只能适用一般的实体类,稍微高级一点的估计都不行,就只是一个学习的笔记,更好的去理解和学习反射

猜你喜欢

转载自blog.csdn.net/qq_31878883/article/details/84785519