Kotlin
反射调用成员方法
class MyClass {
fun MyMethod(param1: String, param2: Int): String {
return "Called Method with param1: $param1, param2: $param2"
}
}
fun myMemberMethodInvoke(target: Class<*>, methodName: String, parameterTypes: Array<Class<*>>, vararg args: Any?) {
try {
val newInstance = target.getDeclaredConstructor().newInstance()
val method: Method = target.getDeclaredMethod(methodName, *parameterTypes)
method.isAccessible = true
val result = method.invoke(newInstance, *args)
println("Method result: $result")
} catch (e: Exception) {
e.printStackTrace()
}
}
fun main() {
val methodName = "MyMethod"
val parameterTypes = arrayOf<Class<*>>(String::class.java, Int::class.java)
val args = arrayOf<Any?>("Hello", 123)
myMemberMethodInvoke(MyClass::class.java, methodName, parameterTypes, *args)
}
Method result: Called Method with param1: Hello, param2: 123
Kotlin
反射调用静态方法
class MyClass {
companion object {
@JvmStatic
fun MyStaticMethod(param1: String, param2: Int): String {
return "Called StaticMethod with param1: $param1, param2: $param2"
}
}
}
fun myStaticMethodInvoke(target: Class<*>, methodName: String, parameterTypes: Array<Class<*>>, vararg args: Any?) {
try {
val method = target.getDeclaredMethod(methodName, *parameterTypes)
val result = method.invoke(null, *args)
println("Static Method Result: $result")
} catch (e: Exception) {
println("Exception: $e")
}
}
fun main() {
val staticMethodName = "MyStaticMethod"
val parameterTypes = arrayOf<Class<*>>(String::class.java, Int::class.java)
val args = arrayOf<Any?>("Hello", 123)
myStaticMethodInvoke(MyClass::class.java, staticMethodName, parameterTypes, *args)
}
Static Method Result: Called StaticMethod with param1: Hello, param2: 123
Kotlin
反射调用注解方法
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class MyAnnotation
class MyClass {
@MyAnnotation
fun MyAnnotatedMethod(param1: String, param2: Int): String {
return "Called Annotated Method with param1: $param1, param2: $param2"
}
}
fun myAnnotationMethodInvoke(target: Class<*>, methodName: String, parameterTypes: Array<Class<*>>, vararg args: Any?) {
try {
val method: Method = target.getDeclaredMethod(methodName, *parameterTypes)
if (method.isAnnotationPresent(MyAnnotation::class.java)) {
val instance = target.getDeclaredConstructor().newInstance()
val result = method.invoke(instance, *args)
println("Annotated Method Result: $result")
}
} catch (e: Exception) {
println("Exception: $e")
}
}
fun main() {
val annotationMethodName = "MyAnnotatedMethod"
val parameterTypes = arrayOf<Class<*>>(String::class.java, Int::class.java)
val args = arrayOf<Any?>("Hello", 123)
myAnnotationMethodInvoke(MyClass::class.java, annotationMethodName, parameterTypes, *args)
}
Annotated Method Result: Called Annotated Method with param1: Hello, param2: 123