Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

スタックトレース

Posted at

class MyClass(private val context: Context) {

fun A() {
    // 呼び出し元のFragmentクラス名とメソッド名を取得
    val callerInfo = getCallerFragmentInfo()

    // トーストに呼び出し元の情報を表示
    Toast.makeText(context, "Called from: $callerInfo", Toast.LENGTH_SHORT).show()
}

// スタックトレースからFragmentを探し、最初に見つけたクラス名とメソッド名を返す
private fun getCallerFragmentInfo(): String {
    val stackTrace = Thread.currentThread().stackTrace

    for (element in stackTrace) {
        val className = element.className
        try {
            val cls = Class.forName(className)
            if (androidx.fragment.app.Fragment::class.java.isAssignableFrom(cls)) {
                val methodName = element.methodName
                return "Class: ${className.substringAfterLast(".")}, Method: $methodName"
            }
        } catch (e: ClassNotFoundException) {
            e.printStackTrace()
        }
    }
    return "No Fragment Found"
}

}

0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?