Kotlin泛型,类型参数的正确语法
我有下面的类,它基本上从AWS获取JSON字符串,然后将其转换为数据类的实例Kotlin泛型,类型参数的正确语法,kotlin,Kotlin,我有下面的类,它基本上从AWS获取JSON字符串,然后将其转换为数据类的实例 class SecretsManager(region: String) { private val gson = Gson() private val smClient = AWSSecretsManagerClientBuilder.standard().withRegion(region).build() fun <T> getSecret(id: String): T {
class SecretsManager(region: String) {
private val gson = Gson()
private val smClient = AWSSecretsManagerClientBuilder.standard().withRegion(region).build()
fun <T> getSecret(id: String): T {
val req = GetSecretValueRequest().withSecretId(id)
val json = smClient.getSecretValue(req).getSecretString()
return gson.fromJson(json, T::class.java)
}
}
class SecretsManager(区域:字符串){
private val gson=gson()
private val smClient=AWSSecretsManagerClientBuilder.standard().withRegion(region.build())
fun getSecret(id:String):T{
val req=GetSecretValueRequest()。带有secretId(id)
val json=smClient.getSecretValue(req).getSecretString()
返回gson.fromJson(json,T::class.java)
}
}
像这样使用
val myInstance = SecretsManager("eu-west-2").getSecret<MyDataClass>("myId")
val myInstance=SecretsManager(“eu-west-2”).getSecret(“myId”)
当前,我收到一个错误-无法使用“T”作为具体化类型参数。我可以通过将函数标记为inline,将T标记为reafied来解决这个问题,但是我不能从函数中访问私有属性
在Kotlin中执行此操作的最佳方法是什么?您需要向
getSecret
方法添加另一个参数,并且还需要添加一个内联具体化方法才能工作。请参见下面的代码
class SecretsManager(区域:字符串){
private val gson=gson()
private val smClient=AWSSecretsManagerClientBuilder.standard().withRegion(region.build())
fun getSecret(类型:Class,id:String):T{
val req=GetSecretValueRequest()。带有secretId(id)
val json=smClient.getSecretValue(req).getSecretString()
返回gson.fromJson(json,类型)
}
内联fun getSecret(id:String):T=getSecret(T::class.java,id)
}
无法访问类型参数的类,因为它们已被擦除。如果不想使t具体化,请接受Class
作为参数将Class
参数添加到当前函数fun-getSecret(id:String,clazz:Class):t
并创建重载函数内联fun-getSecret(id:String,t::Class.java)