简体   繁体   English

Kotlin反射+仿制药

[英]Kotlin reflection + generics

EDIT 1: Changed title, my bad. 编辑1:改变标题,我的坏。

I have an interface Event : 我有一个接口事件

interface Event

And some classes that implement it, like CustomEvent : 还有一些实现它的类,比如CustomEvent

class CustomEvent : Event { ... }

What I've been trying to do now is: given a method that has an event as a parameter (so, any class that implements the Event interface), like this 我现在一直在尝试做的是:给定一个将事件作为参数的方法(所以,任何实现Event接口的类),就像这样

fun onCustomEvent(event: CustomEvent) {
    ...
}

, I want to add that event to a list. ,我想将该事件添加到列表中。 Thus, this list will end up holding a bunch of different events. 因此,这个列表最终将举行一系列不同的事件。


In Java I belive it would be something like this (might not be 100% accurate): Java中我相信它会是这样的(可能不是100%准确):

List<Class<? extends Event>> eventsList;

....

Class<?> param = methodThatHasSomeEventAsParam.parameterTypes[0];

if (Event.class.isAssignableFrom(param)) {
    Class<? extends Event> actualParam = (Class<? extends Event>) param;
    eventsList.add(actualParam); // Adds CustomEvent to the events list.
}

But as for Kotlin, I'm really not sure how to use the generics properly, specifically what would be the correct way to translate 但至于Kotlin,我真的不确定如何正确使用泛型,特别是正确的翻译方式是什么

Class<? extends Event> 

to Kotlin, keeping the same behaviour as the Java code above. 到Kotlin,保持与上面的Java代码相同的行为。

Thanks in advance. 提前致谢。

Thanks for the help; 谢谢您的帮助; this would be the way to do it in Kotlin: 这将是在Kotlin做的方式:

// <? extends Event> in Java ==> <out Event> in Kotlin.
val myList: MutableList<Class<out Event>>

val param: Class<*> = methodThatHasSomeEventAsParam.parameterTypes[0]

if (Event::class.java.isAssignableFrom(param)) {
    param as Class<out Event>
    myList.add(param)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM