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:
댓글 쓰기