Skip to content

Instantly share code, notes, and snippets.

@mmorihiro
Created February 7, 2017 11:19
Show Gist options
  • Save mmorihiro/20dca204abd8fbb611be2a9befddbbd9 to your computer and use it in GitHub Desktop.
Save mmorihiro/20dca204abd8fbb611be2a9befddbbd9 to your computer and use it in GitHub Desktop.
package io.github.config4k
import io.kotlintest.specs.WordSpec
import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl
import sun.reflect.generics.reflectiveObjects.WildcardTypeImpl
import java.lang.reflect.ParameterizedType
import java.lang.reflect.WildcardType
import kotlin.reflect.KClass
import kotlin.reflect.jvm.javaType
import kotlin.reflect.primaryConstructor
class TestReflection : WordSpec() {
init {
"Company.names's type" should {
"be String::class" {
val clazz = Company::class
val type = clazz.primaryConstructor!!
.parameters.find { it.name == "names" }!!.type
val list = getGenericList(type.javaType as ParameterizedType)
list shouldBe listOf(String::class)
}
}
"Company.names2's type" should {
"be List::class, String::class" {
val clazz = Company::class
val type = clazz.primaryConstructor!!
.parameters.find { it.name == "names2" }!!.type
val list = getGenericList(type.javaType as ParameterizedType)
list shouldBe listOf(List::class, String::class)
}
}
}
}
fun getGenericList(type: ParameterizedType): List<KClass<*>> {
val impl =
if (type.actualTypeArguments.size > 1) type.actualTypeArguments[1]
else type.actualTypeArguments[0]
val list = listOf((when (impl) {
is ParameterizedTypeImpl -> impl.rawType
is WildcardTypeImpl -> {
val r = impl.upperBounds[0]
if (r is ParameterizedTypeImpl) r.rawType else r as Class<*>
}
else -> impl as Class<*>
}).kotlin)
return if (impl is WildcardTypeImpl) list + getGenericList(impl.upperBounds[0] as ParameterizedType)
else list
}
class Company(names: List<String>, names2: List<List<String>>)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment