Spring boot 关于kotlin的一般问题
我正在尝试实现一个处理外部API调用的基本函数: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
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)
}
}