[英]Kotlin Reflection Issue
I have these methods declared in Java libraries: 我在Java库中声明了这些方法:
Engine.java: Engine.java:
public <T extends EntitySystem> T getSystem(Class<T> systemType)
Entity.java: Entity.java:
public <T extends Component> T getComponent(Class<T> componentClass)
Now, I use these methods A LOT, and I would really like to use MyComponent::class
(ie kotlin reflection) instead of the more verbose javaClass<MyComponent>()
everywhere. 现在,我使用这些方法A LOT,我真的想在任何地方使用MyComponent::class
(即kotlin反射)而不是更详细的javaClass<MyComponent>()
。
My EntitySystem
and Component
implementations are written in Kotlin. 我的EntitySystem
和Component
实现是用Kotlin编写的。
So I thought I would create extension functions that take KClasses
instead, but I am not quite sure how to make them work. 所以我认为我会创建以KClasses
代替的扩展函数,但我不太确定如何使它们工作。
Something along the lines of... 有点......
public fun <C : Component> Entity.getComponent(type: KClass<out Component>): C {
return getComponent(type.javaClass)
}
But this does not work for several reasons: The compiler says type inference failed, since javaClass
returns Class<KClass<C>>
. 但这不起作用有几个原因:编译器说类型推断失败,因为javaClass
返回Class<KClass<C>>
。 And I need Class<C>
. 我需要Class<C>
。 I also don't know how to make the method properly generic. 我也不知道如何使方法适当通用。
Can anyone help me create these methods? 任何人都可以帮我创建这些方法吗?
In current Kotlin (1.0), the code would be simpler as: 在当前的Kotlin(1.0)中,代码将更简单:
public inline fun <reified C : Component> Entity.getComponent(): C {
return getComponent(C::class)
}
And can be called: 并且可以称为:
val comp: SomeComponent = entity.getComponent()
Where type inference will work, reify the generic type parameter (including any nested generic parameters) and call the method, which then uses the type parameter as a class reference. 在类型推断将起作用的地方,重新通用泛型类型参数(包括任何嵌套的泛型参数)并调用该方法,然后使用类型参数作为类引用。
You should use the extension property java
instead of javaClass
. 您应该使用扩展属性java
而不是javaClass
。
Additionally You can improve your API with reified type parameters and rewrite your code like: 此外,您可以使用reified类型参数改进API并重写代码,如:
public inline fun <reified C : Component> Entity.getComponent(): C {
return getComponent(C::class.java)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.