https://kotlinlang.org logo
#reflect
Title
# reflect
k

kennyyi

08/11/2018, 5:58 AM
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

diesieben07

08/12/2018, 4:30 PM
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

kennyyi

08/13/2018, 6:42 AM
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
        ...
    }
    ...
}