gpt4 book ai didi

java - 如何用反射实例化内部类?

转载 作者:行者123 更新时间:2023-12-02 02:18:05 25 4
gpt4 key购买 nike

我想获取嵌套类的构造函数,以便我可以实例化它。我希望这是一个内部类,以便我可以从其外部类访问变量。

下面的代码抛出 NoSuchMethodException,并添加了 inner 前缀:

package com.example

import android.util.Log

class ClassA {

var iWantToUseThisFromTheInnerClass = "someValue"

fun runThisToStart() {
val classB = ClassB(InnerClassA::class.java)
classB.doSomething()

}

inner class InnerClassA(text: String) {
init {
Log.d("InnerClassA", "Constructor invoked " + text)
}
}

}
<小时/>
package com.example

import java.lang.reflect.InvocationTargetException

class ClassB<T>(private var mModelClass: Class<T>) {

val someText = "whatever"

fun doSomething():T {
try {
val constructor = mModelClass.getConstructor(String::class.java)
return constructor.newInstance(someText)
} catch (e: NoSuchMethodException) { // Throws this exception
throw RuntimeException(e)
} catch (e: InvocationTargetException) {
throw RuntimeException(e)
} catch (e: InstantiationException) {
throw RuntimeException(e)
} catch (e: IllegalAccessException) {
throw RuntimeException(e)
}
}

}

谢谢

最佳答案

您还需要在构造函数中包含封闭类 (ClassA) 实例,因为没有它,InnerClassA 就无法存在:

class ClassA {

var iWantToUseThisFromTheInnerClass = "someValue"

fun runThisToStart() {
val classB = ClassB(InnerClassA::class.java)
classB.doSomething(this)

}

inner class InnerClassA(text: String) {
init {
// Log.d("InnerClassA", "Constructor invoked " + text)
}
}

}

class ClassB<T>(private var mModelClass: Class<T>) {

val someText = "whatever"

fun doSomething(enclosingObj : Any):T {
val constructor = mModelClass.getConstructor(enclosingObj::class.java, String::class.java)
return constructor.newInstance(enclosingObj, someText)
}

}

关于java - 如何用反射实例化内部类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48973775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com