Is there a way to know information of collection? ...
# reflect
k
Is there a way to know information of collection?
Copy code
fun foo(clazz: Class<*>) {
  // 1. How to know clazz is collection?
  // 2. How to know T of Collection<T> is String?
}

fun myFunc() {
  val mySet: HashSet<String> = HashSet()
  foo(mySet::class.java)
}
d
No. At runtime
HashSet<String>
and
HashSet<Foo>
are represented by the same (erased) class
HashSet
. You can do some clever tricks with subclasses and the
reified
keyword, but your example is not possible.
k
Thanks, I solved this issue with making annotation. for example,
Copy code
annotation class ElementType(val element: KClass<*>)

...

@ElementType(String::class)
class Names: HashSet<String>()

...

foo() {
    ...
    val elementType = clazz.annotations.find{ it is ElementType }
    elementType?.let {
        val elementClass = (elementType as ElementType).element
        ...
    }
    ...
}