Kotlin 方法 returns 上使用的 Java 注释的 getAnnotation null
getAnnotation for Java annotation used on Kotlin method returns null
说,我有以下界面:
interface AppRepository : GraphRepository<App> {
@Query("""MATCH (a:App) RETURN a""")
fun findAll(): List<App>
}
在测试中,我想检查查询字符串的细节,因此我这样做了
open class AppRepositoryTest {
lateinit @Autowired var appRepository: AppRepository
@Test
open fun checkQuery() {
val productionMethod = appRepository.javaClass.getDeclaredMethod("findAll")
val productionQuery = productionMethod!!.getAnnotation(Query::class.java)
//demo test
assertThat(productionQuery!!.value).isNotEmpty() //KotlinNPE
}
}
出于某种我不理解的原因,productionQuery
是 nnull
。我仔细检查了测试 class 中导入的 Query
和存储库中的 Query
的类型是否相同。
那么,为什么在这种情况下 productionQuery
null
?
您正在从实现 class(即 appRepository
实例的 class)加载 findAll
上的注释,而不是从 findAll
界面。要改为从 AppRepository
加载注释:
val productionMethod = AppRepository::class.java.getDeclaredMethod("findAll")
val productionQuery = productionMethod!!.getAnnotation(Query::class.java)
说,我有以下界面:
interface AppRepository : GraphRepository<App> {
@Query("""MATCH (a:App) RETURN a""")
fun findAll(): List<App>
}
在测试中,我想检查查询字符串的细节,因此我这样做了
open class AppRepositoryTest {
lateinit @Autowired var appRepository: AppRepository
@Test
open fun checkQuery() {
val productionMethod = appRepository.javaClass.getDeclaredMethod("findAll")
val productionQuery = productionMethod!!.getAnnotation(Query::class.java)
//demo test
assertThat(productionQuery!!.value).isNotEmpty() //KotlinNPE
}
}
出于某种我不理解的原因,productionQuery
是 nnull
。我仔细检查了测试 class 中导入的 Query
和存储库中的 Query
的类型是否相同。
那么,为什么在这种情况下 productionQuery
null
?
您正在从实现 class(即 appRepository
实例的 class)加载 findAll
上的注释,而不是从 findAll
界面。要改为从 AppRepository
加载注释:
val productionMethod = AppRepository::class.java.getDeclaredMethod("findAll")
val productionQuery = productionMethod!!.getAnnotation(Query::class.java)