不得不說 反射真的是個好動
# 貼上我的代碼
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格式字符串
#說明:
由於寫的很簡單,適用的場景很低,只能適用一般的實體類,稍微高級一點的估計都不行,就只是一個學習的筆記,更好的去理解和學習反射