You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin中如何判断Java反射Type是否为字节数组?

Kotlin中判断基本类型数组的正确方式

你遇到的问题核心是Kotlin的KClass和Java的Class类型体系不匹配,导致相等判断失败:

  • 传入的Type实例实际是Java的Class<byte[]>对象,打印显示为byte[]
  • ByteArray::class是Kotlin的KClass类型,即便打印时会显示其对应的Java Class标识class [B,但直接用KClass和Class实例做==比较,因类型归属不同,结果必然为false

正确的判断代码

先确认传入的Type是Class类型(因为Type是接口,数组类型的Type实际就是Class实例),再用Kotlin数组类对应的Java Class对象做比较:

override fun f(t: Type) {
    if (t is Class<*> && t == ByteArray::class.java) {
        doSomething()
    }
}

扩展:其他基本类型数组的判断

对于其他基本类型数组,可采用同样的方式匹配:

  • 短整数数组:ShortArray::class.java 对应 short[]
  • 整数数组:IntArray::class.java 对应 int[]
  • 长整数数组:LongArray::class.java 对应 long[]
  • 字符数组:CharArray::class.java 对应 char[]
  • 布尔数组:BooleanArray::class.java 对应 boolean[]
  • 浮点数数组:FloatArray::class.java 对应 float[]
  • 双精度数组:DoubleArray::class.java 对应 double[]

内容的提问来源于stack exchange,提问作者Pitel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 02:22:09