Reputation: 27
My code ImageI'm writing a class which will give the arrayList of generics, eg: a inline function will take the class name and the output comes as arrayList of that generic class. please help me with this Thanks.
I have a inline function in which creating the generic class instance, and a generic class arrayList, i am trying to add that object of the generic class into arrayList and its working but I am not able to set values to that generic class variables and create instance of that class and add to the arrayList.
"Please check the Code in Image, In code block because of syntax correction some line modified."
// Inline function
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)
}
//===================================================================
// call method
modelClass<testClass> {
// printing the values of list
it.forEach { it ->
Log.d("ModelClass", "ModelClass - " + it.firstName)
}
}
//===================================================================
// model class for reference
class testClass {
var firstName : String = "hi"
get() = field
set(value) {
field = value
}
}
how to add the variable values to the obj as shown in code
"Only getting the default value of variable"
Output :-
ModelClass - hi
Upvotes: 0
Views: 293
Reputation: 27
i found a solution,
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)
}
Upvotes: 0