2022년 10월 10일 월요일

Reflection으로 다른 메쏘드 실행(Kotlin)

Reflection으로 다른 메쏘드 실행(Kotlin)

Reflection 으로 다른클래스 메소드실행

class InvokeMethod(val className: String, val methodName: String) {  
  
/**  
 * 클래스 이름이 있다면 가져옴 */  
 fun getClassInfo(): Class<*>? {  
        return runCatching {  
  Class.forName(className);  
        }.getOrNull()  
    }  
  
 /**  
 * 메소드 이름이 있다면 가져옴 */  
 fun getMethodInfo(classInfo:Class<*>?, parameterTypes:Any?): Method? {  
        return runCatching {  
  parameterTypes?.let {  
  classInfo?.getMethod(methodName, parameterTypes as Class<*>?);  
            }?: run {  
  classInfo?.getMethod(methodName);  
            }  
 }.getOrNull()  
    }  
      
 /**  
 * 메소드 이름이 있다면 가져옴 */  
 fun getMethodFromObject(obj:Any?, methodName:String): Method? {  
        return runCatching {  
  obj?.javaClass?.getMethod(methodName)  
        }.getOrNull()  
    }  
  
    /**  
 * 메소드 실행 */  
 fun <T> invokeM(parameterTypes:Any?, vararg argParam:Any?): T? {  
        val method = getMethodInfo(getClassInfo(), parameterTypes)  
          
        return runCatching {  
            if (argParam.isEmpty()) {  
                method?.invoke(null) as T?  
            } else {  
                method?.invoke(argParam.first(), *argParam.drop(1).toTypedArray()) as T?  
            }  
        }.getOrNull()  
    }  
  
  
 /**  
 * 메소드 실행 */  
 fun <T> invokeFromMethod(method:Method?, vararg argParam:Any?): T? {  
        return runCatching {  
            if (argParam.isEmpty()) {  
                method?.invoke(null) as T?  
            } else {  
                method?.invoke(argParam.first(), *argParam.drop(1).toTypedArray()) as T?  
            }  
  
        }.getOrNull()  
    }  
}

0 comments:

댓글 쓰기