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

Groovy类变量类型转换疑问:Int赋值String为何无报错?

问题代码与疑问
class TestClass{
    String a;
    ArrayList b;
}

TestClass test1 = new TestClass(a: 123) //传入的a值为Int类型,为何未报错?
println test1.a.getClass() //输出'class java.lang.String'。

TestClass test2 = new TestClass(b: 123) //传入的b值同样为Int类型,此时抛出GroovyCastException:Cannot cast object '123' with class 'java.lang.Integer' to class 'java.util.ArrayList'
println test2.b.getClass() //未执行。

疑问

为何给变量a传入Int值时未报错?

我的预期:给变量a传入Int值时,应像变量b一样报错。


原因解析

这是Groovy的自动类型转换机制造成的差异:

  • 针对String类型属性a:Groovy会自动调用传入值的toString()方法完成隐式转换。传入123(Integer类型)时,Groovy会执行123.toString(),将整数转为字符串"123"赋值给a,因此不会报错,最终test1.a的类型为String。
  • 针对ArrayList类型属性b:Groovy没有定义从Integer到ArrayList的合法隐式转换规则,也无法通过默认方法直接将整数转换为ArrayList对象,因此会抛出GroovyCastException类型转换异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 13:17:38