不得不说 反射真的是个好动

贴上我的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
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格式字符串

说明:

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