Created
December 2, 2020 21:41
-
-
Save Almighty-Alpaca/922df2c7b4832802e4089212ff84d058 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.reflect.* | |
import java.lang.reflect.Array | |
import kotlin.reflect.jvm.javaConstructor | |
import kotlin.reflect.jvm.javaMethod | |
fun main() { | |
val clazz: Class<*> = Long::class.java | |
val method = Long::inc | |
val className = clazz.name | |
val methodName = (method.javaMethod ?: method.javaConstructor ?: throw IllegalStateException("$method is neither a method nor a constructor")).name | |
for (executable in Class.forName(className).let { it.methods.toList() + it.constructors }) { | |
if (executable.name == methodName) { | |
val name = when (executable) { | |
is Constructor<*> -> "<init>" | |
is Method -> methodName | |
else -> throw IllegalStateException("Unknown type ${executable.javaClass.name}") | |
} | |
println("${className.replace('.', '/')} $name ${getSignature(executable)}") | |
} | |
} | |
} | |
fun getSignature(e: Executable): String { | |
try { | |
val gSig: Field = when (e) { | |
is Constructor<*> -> Constructor::class.java.getDeclaredField("signature") | |
is Method -> Method::class.java.getDeclaredField("signature") | |
else -> throw IllegalStateException("Unknown type ${e.javaClass.name}") | |
} | |
gSig.isAccessible = true | |
val sig = gSig.get(e) as String? | |
if (sig != null) | |
return sig | |
} catch (e: IllegalAccessException) { | |
e.printStackTrace() | |
} catch (e: NoSuchFieldException) { | |
e.printStackTrace() | |
} | |
val sb = StringBuilder("(") | |
for (type in e.parameterTypes) { | |
sb.append(Array.newInstance(type, 0).toString().substring(1).substringBefore('@').replace('.', '/')) | |
} | |
sb.append(')') | |
val returnType = when (e) { | |
is Constructor<*> -> e.declaringClass | |
is Method -> e.returnType | |
else -> throw IllegalStateException("Unknown type ${e.javaClass.name}") | |
} | |
if (returnType === Void.TYPE) { | |
sb.append("V") | |
} else { | |
sb.append(Array.newInstance(returnType, 0).toString().substring(1).substringBefore('@').replace('.', '/')) | |
} | |
return sb.toString() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment