思路
因为程序不知道具体转化时具体需要处理哪个实体类,所以运用反射机制。获取到传入的类之后,获取该类所有方法,得到该方法的get方法(一般实体类里只有属性,get、set方法吧),通过get方法得到属性的值,并且截取方法名get之后的字段,即为参数名。
代码
package com.nansl.util;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
public class PojoToMap {
public static <T> HashMap<String,String> toMap(T t){
HashMap<String, String> result = new HashMap<String, String>();
Method[] methods = t.getClass().getMethods();
try{
for (Method method:
methods) {
Class<?>[] paramClass = method.getParameterTypes();
if (paramClass.length > 0){
continue;
}
String methodName = method.getName();
if (methodName.startsWith("get")){
Object value = method.invoke(t);
if (value != null)
result.put(methodName.substring(3).toLowerCase(), String.valueOf(value));
}
}
}catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
result.remove("class");
return result;
}
}
map转任意pojo
这个比较麻烦,需要获取到属性的类型,所以我在这里加了几个判断,因为我的实体类中只有三个类型。
public static <T>T mapperObj(Map map, Class<T> t) throws Exception{
if(map==null||map.size()==0){
return t.newInstance();
}
Object tobj=t.newInstance();
System.