使用Singleton对象Kotlin上的反射?

发布于 2025-01-20 14:56:44 字数 8 浏览 1 评论 0原文

continue

I have a use case where I need to use reflection to call method of my singleton class

Singleton class is as below

object Singleton {

fun calledFromReflection(){
    println("Successfull")
}
}

This is how I am using the reflection

val adsUtiltyCls: Class<*>? = Class.forName("com.xia.Singleton")
        val adsUtilityObj: Any? = adsUtiltyCls?.newInstance()
        if (adsUtilityObj != null) {
            val method: Method
            try {
                method = adsUtiltyCls.getDeclaredMethod("calledFromReflection")
                val value=method.invoke(adsUtilityObj)
                println("value   $value")
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

I get the following error

java.lang.IllegalAccessException: void com.com.xia.Singleton.<init>() is not accessible from java.lang.Class<com.xia.RetargetActivity>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

木槿暧夏七纪年 2025-01-27 14:56:44

问题在于,您尝试创建一个已经是一个实例且没有公共构造函数的singleton对象的实例。

为了访问对象实例,您必须更改对象adsutilityObj是相应的Kotlin-Class的对象实例:

val adsUtilityObj = adsUtiltyCls?.kotlin.objectInstance

此外,您可以使用 kotlin反射而不是纯Java反射。然后,您可以写作:

val clazz = Class.forName("com.xia.Singleton").kotlin
clazz.functions.find { it.name == "calledFromReflection" }?.call(clazz.objectInstance)

或等效

Singleton::class.functions.find { it.name == "calledFromReflection" }?.call(Singleton)

The problem is that you try to create an instance of your Singleton object which already is an instance and does not have a public constructor.

In order to access the object instance you have to change your object adsUtilityObj to be the object instance of the corresponding Kotlin-class:

val adsUtilityObj = adsUtiltyCls?.kotlin.objectInstance

Moreover, you could use Kotlin Reflection instead of pure Java reflection. Then you can write:

val clazz = Class.forName("com.xia.Singleton").kotlin
clazz.functions.find { it.name == "calledFromReflection" }?.call(clazz.objectInstance)

or equivalently

Singleton::class.functions.find { it.name == "calledFromReflection" }?.call(Singleton)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文