This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.common.reflect.TypeToken | |
inline fun <reified T> typeToken(): TypeToken<T> = object : TypeToken<T>() { } | |
private val iterableParamType = Iterable::class.java.typeParameters[0] | |
private val mapKeyType = Map::class.java.typeParameters[0] | |
private val mapValueType = Map::class.java.typeParameters[1] | |
fun <T, I : Iterable<T>> TypeToken<I>.elementType(): TypeToken<T> { | |
@Suppress("UNCHECKED_CAST") | |
return resolveType(iterableParamType) as TypeToken<T> | |
} | |
fun <K, M : Map<K, *>> TypeToken<M>.keyType(): TypeToken<K> { | |
@Suppress("UNCHECKED_CAST") | |
return resolveType(mapKeyType) as TypeToken<K> | |
} | |
fun <V, M : Map<*, V>> TypeToken<M>.valueType(): TypeToken<V> { | |
@Suppress("UNCHECKED_CAST") | |
return resolveType(mapValueType) as TypeToken<V> | |
} | |
fun main(args: Array<String>) { | |
val listType = typeToken<List<*>>() | |
val listElementType = listType.elementType() | |
val mapType = typeToken<Map<*, *>>() | |
val mapKeyType = mapType.keyType() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment