kotlin 方法追踪
`
import android.util.Log
import androidx.annotation.IntRange
val StackTraceTag = "stackTraceIndexed"
fun whereUsed(@IntRange(from = 1, to = 10) maxTracking: Int = 10): List
val methodName = object : Any() {}.javaClass.enclosingMethod.name
var stackTrace =
Thread.currentThread().stackTrace.dropWhile { it.methodName != methodName }.drop(1).filter {
!it.methodName.contains("\(")
}
val tag = stackTrace.first().className.split(".").last() + "\)" + stackTrace.first().methodName
Log.d(StackTraceTag, "--------------\(tag「开始追踪」--------------------------")
val res = stackTrace.drop(1).filter {
!it.className.startsWith("android.") && !it.className.startsWith("androidx.") && !it.className.startsWith(
"com.android."
) && !it.className.startsWith("java.")
}.take(maxTracking).apply {
forEach { it ->
Log.d(
tag,
"[ (\){it.fileName}:\({it.lineNumber})#\){it.methodName}] \({it.className} "
)
it
}
}
Log.d(StackTraceTag, "--------------\)tag「结束追踪」 depth:${res.size}--------------------------")
return res
}
fun stackTraceIndexed() = Thread.currentThread().stackTrace.indexOfFirst {
val methodName = object : Any() {}.javaClass.enclosingMethod.name
it.methodName == methodName
}+1
fun currentMethodName() = Thread.currentThread().stackTrace.dropWhile {it.methodName!=object : Any() {}.javaClass.enclosingMethod.name }[1].methodName
`