public class ValueObjectUtil {
private static final Logger LOG = LoggerFactory.getLogger(ValueObjectUtil.class.getName());
/**
* Vo 클래스 값 자동설정
* @param obj 클래스
* @param params key/value map
* @param isOverwrite 덮어쓰기 여부
*/
public static void valueSetting(Object obj, Map<String, Object> params, boolean isOverwrite ){
String methodName = null;
Method setter = null;
Method getter = null;
Object getterVal = null;
for( String key : params.keySet() ){
try {
getterVal = null;
if(!isOverwrite){
methodName = toGetterMethod(key);
getter = getMethod(obj, methodName);
if(getter != null){
getter.setAccessible(true);
getterVal = getter.invoke(obj);
}
}
//값이 없을때만 셋팅
if(getterVal == null){
methodName = toSetterMethod(key);
setter = getMethod(obj, methodName);
if (setter != null) {
setter.setAccessible(true);
setter.invoke(obj, params.get(key));
}
}
} catch (IllegalAccessException e) {
LOG.error("ERROR:",e);
} catch (IllegalArgumentException e) {
LOG.error("ERROR:",e);
} catch (InvocationTargetException e) {
LOG.error("ERROR:",e);
}
}
}
/**
* Vo 클래스 값 자동설정
* @param obj 클래스
* @param request request
* @param isOverwrite 덮어쓰기 여부
*/
public static void valueSetting(Object obj, HttpServletRequest request, boolean isOverwrite ){
Map<String, Object> params = new HashMap<String, Object>();
Enumeration<Object> e = request.getAttributeNames();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
params.put(name, request.getAttribute(name));
}
valueSetting(obj, params, isOverwrite);
}
private static Method getMethod(Object obj, String methodName) {
try {
Method[] methods = obj.getClass().getMethods();
for (Method method : methods) {
if (method.getName().equals(methodName)) {
return method;
}
}
} catch (SecurityException e) {
LOG.error("ERROR:",e);
}
return null;
}
private static String toSetterMethod(String property) {
String setter = "set";
setter += property.substring(0, 1).toUpperCase() + property.substring(1);
return setter;
}
private static String toGetterMethod(String property){
String setter = "get";
setter += property.substring(0, 1).toUpperCase() + property.substring(1);
return setter;
}
}
'Java' 카테고리의 다른 글
POI 엑셀 (0) | 2016.04.20 |
---|---|
class에 annotation 지정하여 모든 메서드에 실행되도록 설정 (0) | 2016.04.04 |
클로저 디자인 패턴 (0) | 2016.02.18 |
java version (0) | 2016.01.27 |
정규식 while 검사 (0) | 2016.01.27 |