使用Singleton对象Kotlin上的反射?
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题在于,您尝试创建一个已经是一个实例且没有公共构造函数的
singleton
对象的实例。为了访问对象实例,您必须更改对象
adsutilityObj
是相应的Kotlin-Class的对象实例:此外,您可以使用 kotlin反射而不是纯Java反射。然后,您可以写作:
或等效
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:Moreover, you could use Kotlin Reflection instead of pure Java reflection. Then you can write:
or equivalently