How to pass Java class as parameter to Kotlin annotation?


#1

Dmitry explained how to pass Kotlin class to Kotlin function in (How to pass class parameter with Generics to function). However, my problem is passing Java class to Kotlin annotation. What can I do to resolve this issue?

// src/main/kotlin/MapperScan.kt
annotation class MapperScan(
  val basePackages: Array<String> = arrayOf(),
  val factoryBean: KClass<out MapperFactoryBean<*>> = MapperFactoryBean::class
)

// src/main/kotlin/MapperFactoryBean.kt
open class MapperFactoryBean<T : Any> : SqlSessionDaoSupport, FactoryBean<T> {
}

// src/test/java/DummyMapperFactoryBean.java
class DummyMapperFactoryBean<T> extends MapperFactoryBean<T> {
}

// src/test/java/MapperScanTest.java
class MapperScanTest {
  @Configuration
  @MapperScan(basePackages = "org.mybatis.spring.mapper", factoryBean = DummyMapperFactoryBean.class)
  public static class AppConfigWithCustomMapperFactoryBean {
  }
}

Error message: Incompatible type.
Found 'java.lang.Class<DummyMapperFactoryBean>',
required 'java.lang.Class<? extends MapperFactoryBean<?>>'

#2

Temporary fix this issue by using wildcard. It should allow only class extended from MapperFactoryBean. I wish Kotlin could read metadata from Java class and know that it’s already extends from MapperFactoryBean.

// src/main/kotlin/MapperScan.kt
annotation class MapperScan(
val basePackages: Array = arrayOf(),
val factoryBean: KClass<*> = MapperFactoryBean::class
)