0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Kotlin】引数にunsigned integersが含まれる関数をKotlin/Javaリフレクションで呼び出す

Posted at

確認はKotlin 1.4.32で行いました。

TL;DR

  • KFunctionを呼び出す場合、unsigned integers型を渡す必要が有る
  • JavaConsturctor/Methodを呼び出す場合、プリミティブ型を渡す必要が有る
    • ただし、符号付きの値がunsigned扱いになるため注意が必要

確認した内容

以下のコンストラクタの呼び出しで確認を行いました。

@ExperimentalUnsignedTypes
data class Temp constructor(
    val uByte: UByte,
    val uShort: UShort,
    val uInt: UInt,
    val uLong: ULong
)

確認に用いたコードは以下の通りです(JavaConstructorに渡しているnullunsigned integersを入れた時に要求されるDefaultConstructorMarkerです)。
結果はコメントに記述した通りです。

// Kotlin上の型で呼べるか
val k0 = kConstructor.call(1.toUByte(), 2.toUShort(), 3.toUInt(), 4L.toULong())
// java.lang.IllegalArgumentException: argument type mismatchになる
// val c0 = constructor.newInstance(1.toUByte(), 2.toUShort(), 3.toUInt(), 4L.toULong(), null)

// プリミティブ型で呼べるか
// java.lang.IllegalArgumentException: object is not an instance of declaring classになる
// val k1 = kConstructor.call(1.toByte(), 2.toShort(), 3, 4L)
val c1 = constructor.newInstance(1.toByte(), 2.toShort(), 3, 4L, null)

補足

JavaConstructorを呼び出す際、例えば負の値を渡すと以下のようになるため注意が必要です。

val c1 = constructor.newInstance((-1).toByte(), 2.toShort(), 3, 4L, null)

println(c1.uByte) // -> 255
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?