Spring boot 关于kotlin的一般问题

Spring boot 关于kotlin的一般问题,spring-boot,generics,kotlin,resttemplate,Spring Boot,Generics,Kotlin,Resttemplate,我正在尝试实现一个处理外部API调用的基本函数: inline fun <reified T> get(url: String): T? { try { val restTemplate = RestTemplate() val response = restTemplate.exchange<Any>( url, HttpMethod

我正在尝试实现一个处理外部API调用的基本函数:

   inline fun <reified T> get(url: String): T? {

        try {

            val restTemplate = RestTemplate()
            val response = restTemplate.exchange<Any>(
                url,
                HttpMethod.GET,
                headersForRestTemplate,
                T::class)

            return response.getBody() as T

        } catch (e: Exception) {
            log.info("Exception ::" + e.message)
            throw ServiceException(e)
        }

    }

返回的对象不是
SWObject
类的实例,而是
LinkedHashMap
。我仍然在努力解决
具体化
内联
关键字,如果我的实现没有遵循最佳实践,很抱歉。

exchange
方法中使用
t::class.java
而不是
t::class
,并从
exchange
方法调用中删除显式类型参数
Any
,因为它变得不必要。您也不需要将响应主体强制转换为
t

inline fun <reified T> get(url: String): T? {
    try {
        val restTemplate = RestTemplate()
        val response = restTemplate.exchange(
            url,
            HttpMethod.GET,
            headersForRestTemplate,
            T::class.java
        )

        return response.getBody()
    } catch (e: Exception) {
        log.info("Exception ::" + e.message)
        throw ServiceException(e)
    }
}

inline-fun-get(url:String):T?{
试一试{
val restTemplate=restTemplate()
val响应=restTemplate.exchange(
网址,
HttpMethod.GET,
headersForRestTemplate,
T::class.java
)
返回响应。getBody()
}捕获(e:例外){
log.info(“异常::”+e.message)
抛出服务异常(e)
}
}
Object::class
返回一个Kotlin类(
KClass
),而
Object::class.java
返回一个java类(
class
),相当于java的
Object.class
)。请注意,
KClass
Class
不同


exchange
方法只希望它的
responseType
参数是
Class
的类型(或者
ParameterizedTypeReference
,但事实并非如此)。

完美的答案,超出了我的预期~还感谢演员技巧!
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to jp.co.xx.demo.models.SWObject
inline fun <reified T> get(url: String): T? {
    try {
        val restTemplate = RestTemplate()
        val response = restTemplate.exchange(
            url,
            HttpMethod.GET,
            headersForRestTemplate,
            T::class.java
        )

        return response.getBody()
    } catch (e: Exception) {
        log.info("Exception ::" + e.message)
        throw ServiceException(e)
    }
}