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

时间:2018-02-25 13:07:59

标签: java android reflection kotlin getconstructor

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

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

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)
        }
    }

}

由于

1 个答案:

答案 0 :(得分:2)

您还需要在构造函数中包含封闭类(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)
    }

}