欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

将POJO对象转成Map

程序员文章站 2022-06-15 09:57:52
...

// POJO
package com.test;
public class Person {

private Integer id;
private String lastName;
private String firstName;

public String getFirstName()
{
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}
}

//测试类

package com.test;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Test {

/**
* @将POJO对象转成Map
*/

public static Map testReflect(Object obj) {
Map hashMap = new HashMap();
try {
Class c = obj.getClass();
Method m[] = c.getDeclaredMethods();
for (int i = 0; i < m.length; i++) {
if (m[i].getName().indexOf("get")==0) {
//System.out.println("方法名:"+m[i].getName());
// System.out.println("值:"+ m[i].invoke(obj, new Object[0]));
hashMap.put(m[i].getName(), m[i].invoke(obj, new Object[0]));
}
}
} catch (Throwable e) {
System.err.println(e);
}
return hashMap;
}

public static void main(String[] args) {

Person p = new Person();
p.setFirstName("张");
p.setId(119);
p.setLastName("三");
Map personMap = Test.testReflect(p);
Iterator it = personMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry map = (Map.Entry) it.next();
System.out.println("方法名:" + map.getKey() + " ,值: "+ map.getValue());
}

}

}



//测试结果
方法名:getLastName ,值: 三
方法名:getId ,值: 119
方法名:getFirstName ,值: 张
相关标签: Java C C++ C#