[英]Getting syntax error in Java code: Cannot cast from Object to int
I keep getting the syntactic error in Java code: 我一直在Java代码中得到语法错误:
Cannot cast from Object to int.
The problem code is like this: 问题代码是这样的:
int a = (int)obj;//obj is of Object type
But I have always been using this trick around, and only get the error recently. 但我一直在使用这个技巧,最近才得到错误。
My question: 我的问题:
Object
to int
is two steps - first you need to convert the Object
to an Integer
, then you need to convert the Integer
to an int
. Object
到int
是两个步骤 - 首先需要将Object
转换为Integer
,然后需要将Integer
转换为int
。
Fortunately auto-boxing will handle the second conversion for you, but you still need to explicitly make the first conversion: 幸运的是,自动装箱将为您处理第二次转换,但您仍需要明确进行第一次转换:
int a = (Integer)obj;
您不能将对象强制转换为基本类型,您需要强制转换为Integer
:
Integer a = (Integer)obj;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.