fluxi fluxi - 4 years ago 328
Java Question

Kotlin Reflection Issue

I have these methods declared in Java libraries:

Engine.java:

public <T extends EntitySystem> T getSystem(Class<T> systemType)


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
(i.e. kotlin reflection) instead of the more verbose
javaClass<MyComponent>()
everywhere.

My
EntitySystem
and
Component
implementations are written in Kotlin.

So I thought I would create extension functions that take
KClasses
instead, but I am not quite sure how to make them work.

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>>
. And I need
Class<C>
. I also don't know how to make the method properly generic.

Can anyone help me create these methods?

Answer Source

You should use the extension property java instead of javaClass.

Additionally You can improve your API with reified type parameters. Unfortunately it doesn't yet work with class literals(related issue) but you can use javaClass<T>().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download