Skip to content

Commit 5d1804d

Browse files
author
seal
committed
add support reflect overload methods in package level
1 parent 8a54c6a commit 5d1804d

File tree

3 files changed

+26
-5
lines changed

3 files changed

+26
-5
lines changed

library/src/androidTest/java/wu/seal/android/kotlinreflecttools/ReflectToolTest.kt

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,4 +171,20 @@ class ReflectToolsKtTest {
171171
expectedObjMethodValue.should.be.equal(returnValue)
172172

173173
}
174+
175+
@Test
176+
fun invokeTopMethodByMethodNameWithDifferentArguments() {
177+
var result = invokeTopMethodByMethodName(::topName as CallableReference, "gotIt")
178+
result.should.be.equal(true)
179+
180+
result = invokeTopMethodByMethodName(::topName as CallableReference, "gotIt", false)
181+
result.should.be.equal(false)
182+
183+
result= try {
184+
invokeTopMethodByMethodName(::topName as CallableReference, "gotIt", "Wrong")
185+
} catch (e: Exception) {
186+
"Wrong"
187+
}
188+
result.should.be.equal("Wrong")
189+
}
174190
}

library/src/androidTest/java/wu/seal/android/kotlinreflecttools/TestThings.kt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ private val topAge = 666
1111
private val topAgeName = "666"
1212

1313
private fun gotIt() = true
14+
private fun gotIt(boolean: Boolean) = boolean
1415
private fun preTopAge(): Int {
1516
return funPropertyReduceAge(topAge)
1617
}

library/src/main/java/wu/seal/android/kotlinreflecttools/KotlinRefelectForAndroid.kt

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -173,13 +173,17 @@ fun invokeTopMethodByMethodName(otherCallableReference: CallableReference, metho
173173
throw IllegalArgumentException("No such property 'jClass'")
174174
}
175175
containerClass.declaredMethods.forEach { method ->
176-
if (method.name == methodName) {
176+
if (method.name == methodName && method.parameterTypes.size == methodArgs.size) {
177177
method.isAccessible = true
178178

179-
if (methodArgs.isNotEmpty()) {
180-
return method.invoke(null, *methodArgs)
181-
} else {
182-
return method.invoke(null)
179+
try {
180+
if (methodArgs.isNotEmpty()) {
181+
return method.invoke(null, *methodArgs)
182+
} else {
183+
return method.invoke(null)
184+
}
185+
} catch (e: Exception) {
186+
return@forEach
183187
}
184188
}
185189
}

0 commit comments

Comments
 (0)