简体   繁体   中英

Kotlin generic function response

I'm trying to write a generic function which reads a json string from file and parses it into a expected object. Expected object is a data class.

fun <T: Any> read(fileName: String, type: KClass<T>): T? {
    val file = File(fileName)
    if(!file.exists()) {
        return null
    }
    val str = file.readText()
    val data = Gson().fromJson<T>(str, type::class.java)
    return data
}

It works until json parsing, which unfortunately creates a object of type class kotlin.reflect.jvm.internal.KClassImpl .

I would expect the response of

val data = Gson().fromJson<T>(str, type::class.java)

to be T . How to get a return object of type T ?

When trying to run the function above it throws the following exception:

java.lang.ClassCastException: kotlin.jvm.internal.ClassReference cannot be cast to my.app.Models.DemoModel

You need to replace ::class.java with .java . Alternatively, you can rewrite it like this:

inline fun <reified T: Any> read(fileName: String): T? {
    val file = File(fileName)
    if(!file.exists()) {
        return null
    }
    val str = file.readText()
    val data = Gson().fromJson<T>(str, T::class.java)
    return data
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM