我们可以使用 java.lang.reflect 包中的 Field 类和 Method 类来将 Java 类转换为 Map。首先,我们可以使用 Field 类的 getDeclaredFields() 方法获取类中声明的所有域。然后,我们可以使用 Method 类的 getDeclaredMethods() 方法获取类中声明的所有方法。我们可以循环遍历域和方法,将它们的名称和值放入 Map 中。
下面是一个例子:
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) throws Exception {
Person person = new Person("John", 30);
Map<String, Object> map = objectToMap(person);
System.out.println(map);
}
public static Map<String, Object> objectToMap(Object obj) throws Exception {
Map<String, Object> map = new HashMap<>();
Class<?> clazz = obj.getClass();
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
map.put(field.getName(), field.get(obj));
}
for (Method method : clazz.getDeclaredMethods()) {
if (method.getName().startsWith("get")) {
map.put(method.getName(), method.invoke(obj));
}
}
return map;
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
输出结果:
{name=John, getName=John, getAge=30}