반응형
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class CommonObjectUtils {
public static Map convertObjectToMap(Object obj){
Map map = new HashMap();
Field[] fields = obj.getClass().getDeclaredFields();
for(int i=0; i <fields.length; i++){
fields[i].setAccessible(true);
try{
map.put((fields[i].getName()), fields[i].get(obj));
}catch(Exception e){
e.printStackTrace();
}
}
return map;
}
public static Object convertMapToObject(Map<String,Object> map,Object obj){
String keyAttribute = null;
String setMethodString = "set";
String methodString = null;
Iterator itr = map.keySet().iterator();
while(itr.hasNext()){
keyAttribute = (String) itr.next();
methodString = setMethodString+keyAttribute.substring(0,1).toUpperCase()+keyAttribute.substring(1);
Method[] methods = obj.getClass().getDeclaredMethods();
for(int i=0;i<methods.length;i++){
if(methodString.equals(methods[i].getName())){
try{
methods[i].invoke(obj, map.get(keyAttribute));
}catch(Exception e){
e.printStackTrace();
}
}
}
}
return obj;
}
}
반응형
'Back > Spring Java' 카테고리의 다른 글
No 'Access-Control-Allow-Origin' header is present on the requested resource. (CORS policy) (0) | 2020.03.02 |
---|---|
CamelCase, SnakeCase Convert Function (0) | 2020.01.14 |
JPA findAll Specification (0) | 2020.01.14 |
BeanUtils.copyProperties (0) | 2019.12.23 |
Blob형태의 이미지 파일 입출력 (0) | 2019.12.19 |