처리 결과가 statusCode에 따라 분기되야하는 코드가 있다고 하자.
statusCode에 따라 if else처리를 할 수도 있지만 코드도 길어지고 보기에도 좋지 않다.
각 statusCode에 따라 분기처리해야 할 기능을 method로 정의해놓고 java.lang.reflect을 이용하여 Method를 invoke하여 if else를 사용하지 않는 코드를 만든다.
1. 각 상태코드마다 실행할 method를 정의한 Enum을 생성
public enum StatusMethod {
STATUS_SUCCESS("processSuccess"),
STATUS_NOTUSER("processNotUser"),
STATUS_STOP("processStop"),
STATUS_WARN("processMig"),
STATUS_MIG("processWarn");
String handelMethodName;
public String getHandelMethodName() {
return handelMethodName;
}
LoginStatusMethod(String handleMethodName) {
this.handelMethodName = handleMethodName;
}
}
2. enum으로부터 처리할 method명을 가져와 해당 Method를 invoke 한다.
import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
public ModelAndView actionProcess(String statusCode, HttpServletRequest request) {
Class thisClass = this.getClass();
Class[] paramType = {HttpServletRequest.class};
Method executeMethod = null;
try {
executeMethod = thisClass.getMethod((StatusMethod.valueOf("STATUS_"+statusCode)).getHandelMethodName(), paramType);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
ModelAndView mv = null;
try {
mv = (ModelAndView) executeMethod.invoke(this, request);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
return mv;
}
enum에서 handelMethodName대신 class name을 쓴다면 java.lang.reflect.Method 대신 ApplicationContext의 getBean을 사용하면 된다.
댓글