https://kotlinlang.org logo
#stdlib
Title
# stdlib
z

Zoltan Demant

08/24/2022, 3:50 AM
I can do
Class<T>.newInstance()
to invoke a no-args constructor of T. Is it possible to do something similar for an object in kotlin while only having access to
Class<T>
where I know that T is an object, without using reflection?
T::class.objectInstance
seems to do what I want, but with the help of reflection.
e

ephemient

08/24/2022, 4:08 AM
there's not much you can do with a
Class<?>
aside from reflection. or are you not counting Java reflection?
z

Zoltan Demant

08/24/2022, 4:20 AM
Slowly learning that 😞 I dont want to use java reflection either.
s

spand

08/25/2022, 7:23 PM
Maybe you can reorder your code and accept a
() -> T
(the constructor) and derive
Class<T>
from that
z

Zoltan Demant

08/26/2022, 2:17 AM
@spand Normally that would work, but I dont have access to T directly unfortunately! Im parsing values from an okio buffer, so I can derive the Class<T> of the value, and based on that I know that certain T are objects, but I cant find a neat way to avoid boilerplate for all of them (there are roughly 50).
6 Views