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
相关产品推荐
相关产品推荐

