-2

/** this "T::class.java" report an error :Cannot use 'T' as reified type parameter. Use a class instead! so how can i fix it or what can i do to realize this way?please. **/ see the next kotlin code

data class PostHttpResultBean<T>(private var errno:Int,private var error:String,private var data:String):IHttpResultEntity<T>{
override val errorCode: Int
    get() = errno
override val errorMessage: String
    get() = error
override val isSuccess: Boolean
    get() = errno==0
override val result:T
    get() = RSAUtil.dataDecrypt(RSAUtil.getKeyPassword(), data,T::class.java)!!

class RSAUtil {
companion object {
fun <T> dataDecrypt(password: String, data: String, java: Class<T>): T? {
    val content = Base64.decode(data.toByteArray(), Base64.NO_WRAP)
    try {
        var deString = decrypt(content, password)
        if (!deString.isEmpty()){
            val first = deString.substring(0, deString.lastIndexOf(":") + 1)
            deString = "$first$deString}"
            return Gson().fromJson(deString,java)
        }

        return null
    } catch (e: Exception) {
        e.printStackTrace()
    }

    return null
 }
 }
 }
Nikos Hidalgo
  • 3,666
  • 9
  • 25
  • 39
AndroidMose
  • 3
  • 1
  • 3

1 Answers1

0

You should change dataDecrypt like that:

inline fun <reified T> dataDecrypt(password: String, data: String): T? {
     ...
     try {
          ...
          if (!deString.isEmpty()){
              ...
              return Gson().fromJson(deString, T::class.java)
          }
          ...
     }
 }

And on the call site the T type will be inferred from result:

override val result:T
get() = RSAUtil.dataDecrypt(RSAUtil.getKeyPassword(), data)!!

You can read more about inline functions and reified types here and I strongly recommend to do so. I would also point out that your code is ill-formatted, it is advised to use ?: instead of !! in nullability checks and companion objects are discouraged in Kotlin, you could define functions outside of class and use (or import) them as if they were static.

Jakub Licznerski
  • 1,008
  • 1
  • 17
  • 33