获取Java/Kotlin类的所有方法签名
MethodSignKotlinUtils(Kotlin)
需要依赖: implementation "org.jetbrains.kotlin:kotlin-reflect:1.4.21"
import kotlin.reflect.KClass
import kotlin.reflect.full.*
/**
* # 获取Kotlin类的所有方法签名
*
* - 需要依赖: implementation "org.jetbrains.kotlin:kotlin-reflect:1.4.21"
*
* 1. 获取Java类的所有方法签名 https://blog.csdn.net/weixin_38106322/article/details/108218774
*
* 2. Kotlin反射 https://www.jianshu.com/p/63da6197913b
*/
object MethodSignKotlinUtils {
@JvmStatic
fun main(args: Array<String>) {
printMethodSignForKotlin(TestReflect::class)
}
private fun printMethodSignForKotlin(clazz: KClass<*>) {
println("-------------------------------------------------------------")
//获取该对象声明的全部方法
//fun com.ando.file.sample.TestReflect.see(): kotlin.String 去掉包名简化 fun see(): kotlin.String
val declaredFunctions = clazz.declaredFunctions
declaredFunctions.forEach {
val prefix = "${clazz.qualifiedName}."
var func = "$it"
func = func.replace(prefix, "")
println(func)
}
println("-------------------------------------------------------------")
}
}
🌴 如果是Android Studio, 执行Run.... with Coverage
🍎 运行结果
会报一堆
Class data was not extracted不用管.
MethodSignJavaUtils(Java)
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/**
* 获取Java类的所有方法签名
* <p>
* https://blog.csdn.net/weixin_38106322/article/details/108218774
*/
public class MethodSignJavaUtils {
public static void main(String[] args) {
printMethodSign(new String("666"));
}
private static <T> void printMethodSign(T t) {
//获取对象类信息
Class<?> aClass = t.getClass();
//获取类中方法
Method[] methods = aClass.getDeclaredMethods();
//遍历方法
System.out.println("-------------------------------------------------------------");
for (Method method : methods) {
//获取方法修饰符
String mod = Modifier.toString(method.getModifiers());
//先拼接修饰符+方法名+'('
System.out.print(mod + " " + method.getName() + "(");
//获取方法参数类型
Class<?>[] parameterTypes = method.getParameterTypes();
//如果没有参数,那就直接拼接上+')'
if (parameterTypes.length == 0) {
System.out.print(")");
} else {
//有参数则遍历
for (int i = 0; i < parameterTypes.length; i++) {
//没到最后一位参数,都用',',否则使用')'最收尾
char end = i == parameterTypes.length - 1 ? ')' : ',';
//输出参数
System.out.print(parameterTypes[i].getSimpleName() + end);
}
}
//为每个方法换行
System.out.println();
}
System.out.println("-------------------------------------------------------------");
}
}
🍎 运行结果
附TestReflect
class TestReflect {
init {
val holiday: Int = 1992
}
companion object {
const val DEFAULT_NAME = "Tony"
lateinit var hobby: String
fun sleep(): Boolean {
return false
}
}
constructor()
constructor(name: String)
private var title: String? = null
val age: String by lazy { "18" }
fun say(): Int {
return 1
}
fun say(block: (text: String) -> Boolean) {}
private fun see(): String {
return ""
}
}
参考
-
获取Java类的所有方法签名 blog.csdn.net/weixin_3810…
-
Kotlin反射 www.jianshu.com/p/63da61979…

浙公网安备 33010602011771号