1

I use a Proxy call another Proxy failed. Always throws argument type mismatch exception. Is there anyone who can help?

Here is the code.

// 1, use mybatis sqlSessionFactory create a Proxy object for MapperProxy.
@Suppress("UNCHECKED_CAST")
private fun <T> createMapper(sqlSessionFactory: SqlSessionFactory, clazz: Class<T>): T {
    return Proxy.newProxyInstance(
        clazz.classLoader,
        arrayOf(clazz),
        KtMapperProxy(
            sqlSessionFactory.configuration.getMapper(
                clazz,
                sqlSessionFactory.openSession()
            )
        )
    ) as T
}

// 2, this class is the Proxy class.
class KtMapperProxy<T>(private val mapper: T) : InvocationHandler {
    override fun invoke(proxy: Any, method: Method, args: Array<Any?>?): Any {
        return method.invoke(mapper, args)
    }
}

// 3, here is the UserMapper class method be called.
fun getById(@Param("id") id: Long): User

// 4, this is test.
@Test
fun `test mapper query`() {
    val userMapper = DataSourceHelper.getMapper(sqlSessionFactory, UserMapper::class.java)
    assertEquals(userMapper.getById(1L).username, "user_1")
}
w-0821
  • 31
  • 4

1 Answers1

2

I figured out the problem。I should spread args when call a method with vararg param。So,it should be method.invoke(mapper, *args) rather then method.invoke(mapper, args)。

w-0821
  • 31
  • 4