반응형

가끔 DB에 입력할 값하고 기존에 있던 값하고 비교해야 할 상황이 생긴다.

그럴때마다 객체에 있는 수많은 getter 메소드를 소스 코드에 써줘야 한다면 코드가 참 지저분할것 같다.

그래서 사용한 방법이 Reflection 이다.

Class에 있는 정보를 읽어와서 실제로 메소드까지 실행 가능하니.. 라인수를 확 줄일 수 있다. ^^

  1. import java.lang.reflect.Method;
  2. public class ReflectionTest {
  3.     public static void main(String[] args) throws Exception {
  4.         // DB에 입력하려는 DATA
  5.         TestVO test = new TestVO();
  6.         test.setId("test");
  7.         test.setName("kim");
  8.         test.setAddr("seoul");
  9.         test.setHobby("game");
  10.        
  11.         printModifyValue(test);
  12.     }
  13.  
  14.     private static void printModifyValue(TestVO test) throws Exception{
  15.         // 값을 비교할 객체에 있는 METHOD를 가져옴
  16.         Method method[] = test.getClass().getDeclaredMethods();
  17.        
  18.         // DB에 현재 존재하는 DATA(DB 연결시에는 DB에서 DATA를 가져오면 됨)
  19.         TestVO testFromDB = new TestVO();
  20.         testFromDB.setId("testDB");
  21.         testFromDB.setName("kim");
  22.         testFromDB.setAddr("Pusan");
  23.         testFromDB.setHobby("music");
  24.        
  25.         // reflection을 이용한 get method  실행
  26.                 for (int i=0; i < method.length; i++){
  27.             String methodName = method[i].getName();
  28.             if (methodName.indexOf("get") != -1){
  29.                 Object inputValue = method[i].invoke(test, null);
  30.                 Object dbValue = method[i].invoke(testFromDB, null);
  31.                
  32.                 // inputValue 가 null, "" 일경우
  33.                 // dbValue 가 null 인데 inputValue 가 "" 인 경우
  34.                 // dbValue 가 "" 안데 inputValue 가 null 인 경우
  35.                 // inputValue 와 dbValue 가 같을 경우
  36.                 if (inputValue == null || "".equals(inputValue) ||
  37.                     dbValue == null && "".equals(inputValue) ||
  38.                     "".equals(dbValue) && inputValue == null ||
  39.                     dbValue.equals(inputValue)){
  40.                     continue;
  41.                 }else if (!dbValue.equals(inputValue)){
  42.                     // 한쪽만 NULL 이거나 값이 서로 같지 않으면 컬럼 값이 변경된 것으로 인식
  43.                     System.out.println("dbValue = " + dbValue + "/ inputValue = " + inputValue);
  44.                 }
  45.             }
  46.         }
  47.     }
  48. }

결과

dbValue = Pusan/ inputValue = seoul 
dbValue = music/ inputValue = game 
dbValue = testDB/ inputValue = test



728x90
반응형

'Development > Java' 카테고리의 다른 글

util.Date vs sql.Date 차이  (0) 2014.07.01
JSP 용량초과? 65535 bytes limit  (0) 2013.11.21
Integer.paserInt 를 사용한 진법 변환  (0) 2013.11.12
Null Object 사용  (0) 2013.07.05
Singleton Pattern  (0) 2013.07.03

+ Recent posts