天天看点

自己写的两个方法,关于bean和map的转化,比网上的效率快很多

public static <T> T  convertMap(Map map, Class<T> tc) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException, InstantiationException{

T t = tc.newInstance();

Iterator it=map.entrySet().iterator();

Method [] methods=tc.getDeclaredMethods();

while(it.hasNext()){ 

Map.Entry entry=(Map.Entry)it.next();

String methodName="set"+BeantoMap.fristToUpperCase(entry.getKey().toString());

for(Method method:methods){

if(method.getName().equals(methodName)){

Object value=entry.getValue();

method.invoke(t, value);

break;

}

}

}

return t;

}

public static String fristToUpperCase(String str){

str=str.substring(0,1).toUpperCase()+str.substring(1,str.length());

return str;

}

public static String fristToLowerCase(String str){

str=str.substring(0,1).toLowerCase()+str.substring(1,str.length());

return str;

}

public static Map convertBean(Object obj) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException{

Class cla=obj.getClass();

Method [] methods=cla.getDeclaredMethods();

Map map =new HashMap();

for(Method method: methods){

if(method.getName().startsWith("get")){

String name=method.getName().substring(3,method.getName().length());

String key =BeantoMap.fristToLowerCase(name);

Object value = method.invoke(obj);

if(null!=value)map.put(key, value);

}

}

return map;

}