Kotlin 检查并访问 List<Any> 中的 class

Kotlin Check and access a class from List<Any>

如何从 Any 数组中检查和访问 adViewClass?

val adViewClass = AddViewClass(name = "an instance")
val elements = listOf("trevor", "john", adViewClass, "0goo")

如何从列表

中获取adViewClass

您可以使用简单的 elementAt 来获得 class

elements.elementAt(2)

elementAt() is useful for collections that do not provide indexed access, or are not statically known to provide one. In case of List, it's more idiomatic to use indexed access operator (get() or []).

并使用 is

检查 class
if (obj is AdViewClass) {

We can check whether an object conforms to a given type at runtime by using the is operator

您可以使用 filterIsInstance(Class<>)

获取列表中特定 class 的所有实例
val elements: List<Any> = listOf<Any>("trevor", "john", AdViewClass, "0goo")
val listOfAdViewClass = elements.filterIsInstance(AdViewClass::class.java)

筛选后的列表将包含列表中 class 的所有实例。