【问题标题】:Generic class object create and set the value to variables of that generic class, object of the generic add to arrayList泛型类对象创建并将值设置为该泛型类的变量,泛型对象添加到arrayList
【发布时间】:2019-09-24 14:52:10
【问题描述】:

My code Image我正在编写一个类,它将给出泛型的arrayList,例如:内联函数将采用类名,输出作为该泛型类的arrayList。请帮我解决这个问题。

我有一个内联函数,在其中创建泛型类实例和一个泛型类 arrayList,我试图将该泛型类的对象添加到 arrayList 及其工作中,但我无法为该泛型类设置值变量并创建该类的实例并添加到arrayList。

“请检查图像中的代码,在代码块中,由于语法更正,某些行已修改。”

//内联函数

inline fun modelClass(Val: (va: ArrayList) -> Unit) {

       // instance of generic class
        var obj = T::class.java.newInstance()

       // how to set values to the variable of "obj" ?

        // generic arrayList 
        var list = ArrayList<T>()

        // adding object to the list
        list.add(obj)
        list.add(obj)

        Val(list)
}

//=============================================== =======================

//调用方法

modelClass<testClass> {
        // printing the values of list
        it.forEach { it ->
            Log.d("ModelClass", "ModelClass - " + it.firstName)
        }
    }

//=============================================== =======================

//模型类供参考

类测试类{

var firstName : String = "hi"
    get() = field
    set(value) {
        field = value
    }

}

如何将变量值添加到obj中,如代码所示

"只获取变量的默认值"

输出:-

ModelClass - 嗨

【问题讨论】:

  • 请注意,如果您完全跳过反射并传入重构,调用modelClass(::T) 而不是modelClass&lt;T&gt;(),这可能会容易得多。
  • @LouisWasserman 感谢您的快速回复,您能告诉我如何通过代码来实现吗?

标签: generics kotlin


【解决方案1】:

我找到了解决办法,

inline fun modelClass(Val: (va: ArrayList) -> Unit) {

   // generic arrayList 
   var list = ArrayList<T>()

   var jacksonObjectMapper = jacksonObjectMapper()

   var map = WeakHashMap<String, String>()
   map["key"] = "value"

   var obj = jacksonObjectMapper.convertValue(map, T::class.java)

    // adding object to the list
    list.add(obj)

    Val(list)

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-04
    • 1970-01-01
    • 2016-09-06
    • 2019-07-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-08
    • 1970-01-01
    相关资源
    最近更新 更多