Hey guys, using Gson, I made a generic method that...
# announcements
o
Hey guys, using Gson, I made a generic method that performs a deep copy on an object.
Copy code
inline fun<reified T> Any.deepCopy(): T {
    val JSON = Gson().toJson(this)
    return Gson().fromJson(JSON, T::class.java)
}
However, when I try to perform this Deep Copy on a List, the items on the list are
LinkedTreeMap
. Can anyone correct me as what can I possible do to resolve it?
d
Are you sure that you call deepCopy with T=ArrayList<Applicant> and not with T=Any?
j
Please never use Gson. Signed, one of its maintainers.
😅 4
😂 5
👍 1
o
Lol, too late my friend @jw
Hmm, I am not sure @David Eriksson How can I debug this? Breakpoints on a generic function doesn't seem to allow me intercepting type T. Anyway, I just found this SO article - https://stackoverflow.com/questions/32444863/google-gson-linkedtreemap-class-cast-to-myclass Seems that there might be something with Java Type erasure. Not sure what that is, I will research
d
Just breakppint in fromJson and examine the clazz
o
@David Eriksson Yes, when debugging "this" I get T = ArrayList<Applicant>:
b
I would try to use TypeToken instead of T::class.java
so it will be
Copy code
return Gson().fromJson(JSON, object : TypeToken<T>() {}.type)
but it should work without it too, are you sure you're calling it as
someObject.deepCopy<ArrayList<Applicant>>
? this ref isn't what David asked, he asked you to enter into fromJson method, and examine what is passed as T::class.java
I would suggest changing Any -> T in signature, then type inference know what is T without writing it in
<>
o
@bezrukov Ohh, here is
T::class.java
, something seems not right Sorry if I seem confused, I am a junior dev As for the TypeToken, it works perfectly, thank you! I just need to research and understand why hahaha
j
It's because
T::class.java
is
ArrayList.class
and there's no type information for the contained items. You can use
typeOf<T>
to get a KType and then get a Type from that
👍 1
🤩 1
496 Views