SSISO Community

시소당

invoke 사용하여 동적으로 함수실행

정해져  있지  않은  클래스에  get,  set  함수를  찾아  자동으로  함수를  실행하여  데이타를  넣고  빼는데
그  목적이  있다.

공통함수로  뽑아서  클래스  명만  파라미터로  리턴받아  어떻게  위의  목적을  실행할까?

먼저  클래스의  모든  함수명에  해당하는  java.lang.reflect.Method  객체  배열을  얻어와야될것이다.
그리고  java.lang.reflect.Method  클래스의  invoke  함수를  사용하면  된다.
클래스의  모든  필드나  함수객체를  가져오기  위해선  메모리에  올려야  한다.
그  역활은  Class.forName(String  [클래스경로])  을  사용한다.  
실행을  위해선  리턴받은  Class  객체를  Class::newInstance  사용하여  메모리에  올린다.
위의  과정을  거쳐서  Method  객체를  가져오면  그  이름으로  어떤  것을  사용할지  결정하고  
실행하면될것이다.  

추가해야될사항은  invoke  에서  파라미터로  데이타를  넘길때  각  필드의  클래스  형태에  맞춰서  넣는
코드를  추가한다.  String,  Integer,  Date  등등  

public  void  inputData(String  className){
        String[]  column  =  new  String[]{"id","mailAddr","text"};
    
        try  {
            //  className  =  "demon.model.MailList"
            Class  clsMailList  =  Class.forName(className);  //  클래스로딩
            Object  obj  =  clsMailList.newInstance();  //  인스턴스  생성
            List  allSetMethods  =  allSetMethods(clsMailList);  //  모든  set  함수를  가져오는  자체함수
            
            for  (int  i=0;  i  <  allSetMethods.size();  i++){
                    Method  method  =  (Method)allSetMethods.get(i);
                    method.setAccessible(true);
                    for  (int  j=0;  j  <  column.length;  j++){
                          String  methodName  =  "set"  +  column[j];
          
                          //  대문자로  변환하여  같은지  비교  
                          if  (methodName.toUpperCase().equals(method.getName().toUpperCase())){
                                  method.invoke(obj,  new  Object[]{"aaa"});
                          }
                  }
                  method.setAccessible(false);
          }

      }  catch  (SecurityException  e)  {
              e.printStackTrace();
      }  catch  (IllegalArgumentException  e)  {
              e.printStackTrace();
      }  catch  (ClassNotFoundException  e)  {
              e.printStackTrace();
      }  catch  (InstantiationException  e)  {
              e.printStackTrace();
      }  catch  (IllegalAccessException  e)  {
              e.printStackTrace();
      }  catch  (InvocationTargetException  e)  {
              e.printStackTrace();
      }
}

public  List  allSetMethods(Class  claz){
    List  methods  =  new  ArrayList();
    List  returnMethods  =  new  ArrayList();
    Class  parent  =  claz;
    
    do{
          methods.addAll(Arrays.asList(claz.getDeclaredMethods()));
          parent  =  parent.getSuperclass();
    }  while(!parent.equals(Object.class));
    
    for  (int  i=0;  i  <  methods.size();  i++){
          Method  method  =  (Method)methods.get(i);
          if  (method.getName().substring(0,3).equals("set")){
                  returnMethods.add(method);
          }
    }
    return  returnMethods;
  }

1914 view

4.0 stars