amadeu01
03/25/2020, 6:37 PMT::class.java.newInstance() // Where T is a generic type
But, if I want to make an new object that need to receive an argument.
The usage of this would be in a recycler view where I have different view holders but each one has a constructor with only one argument. like
inner class ShortTextViewHolder(
private val viewBinding: ItemRowFormFieldTextBinding
) : RecyclerView.ViewHolder(viewBinding.root), FieldViewHolder {
override fun configureWith(field: FormField) = viewBinding.run {
with(field) {
textFieldName.text = label
textFieldDescription.text = description
}
}
}
So basically, I would like to simplify this
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val view = ItemRowFormFieldTextBinding.inflate(parent.inflater)
if (viewType == ITEM_TYPE_SHORT_TEXT) {
return ShortTextViewHolder(view)
}
return LongTextViewHolder(view)
}
By calling a Factory like factory<LongTextViewHolder>(view)
or factory(view, myPossibleTypes[viewType])
where myPossibleTypes
would be a list of the types I can instantiatearaqnid
03/25/2020, 10:27 PMgetConstructor(..)
and call newInstance(..)
on the Constructor returned rather than simply calling newInstance
on the class (which is a shortcut for .getConstructor().newInstance()
)Thiago
03/25/2020, 10:27 PMdata class ViewHolder(val name: String)
inline fun <reified T> check() {
val instance = T::class.constructors.first().apply {
isAccessible = true
}.call("Amadeu")
println(">>>>> My name is: $instance")
}
fun main() {
check<ViewHolder>()
}
Warning: I don't recomend to use reflection in the Android context, because can create bugs not easy to find.Thiago
03/25/2020, 10:27 PMkotlin-reflect
dependencyamadeu01
03/25/2020, 11:40 PMinline fun <reified Field: FieldHolder, View: ViewBinding> myFactory(view: View, init: (View) -> Field): Field {
return init(view)
}
myFactory<ShortTextViewHolder, ItemRowFormFieldTextBinding>(view, ::ShortTextViewHolder)
// or
val field = myFactory(view, ::ShortTextViewHolder)
Which is basically calling the constructor.
Is this ::MyClass
using reflection ?araqnid
03/26/2020, 1:52 AM{view -> ShortTextViewHolder(view) }
lambda