[英]Kotlin reflection: Is it possible to use KProperty1 and omit the class when the type is known through Generics
[英]Is it possible to use all possible types from reflection as generic type?
我正在嘗試使用反射為某些類自動創建 savedStateHandle。
fun <T> KProperty1<T, *>.argFrom(handle: SavedStateHandle) =
when (this.returnType.javaType) {
String::class.java -> handle.get<String>(this.name)
Int::class.java -> handle.get<Int>(this.name)
Uri::class.java -> handle.get<Uri>(this.name)
else -> throw RuntimeException("Type not implemented yet")
}
如您所見,如果類型是例如String
,那么我希望 get 函數的返回類型為String
,並且在這樣做時,我必須手動定義每個案例。
如果我能做這樣的事情就好了。
fun <T> KProperty1<T, *>.argFrom(handle: SavedStateHandle) =
handle.get<this.returnType.javaType>(this.name)
您需要一個類型參數作為屬性的返回類型。 然后您可以使用該類型參數來指定所需的get
返回類型:
fun <T, V> KProperty1<T, V>.argFrom(handle: SavedStateHandle) =
handle.get<V>(this.name)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.