程式碼追蹤

烟花易冷心易碎發表於2024-11-01

package com.example.demo

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
}
fun currentMethodName() = Thread.currentThread().stackTrace.dropWhile {it.methodName!=object : Any() {}.javaClass.enclosingMethod.name }[1].methodName

相關文章