简体   繁体   English

在Java代码中获取语法错误:无法从Object转换为int

[英]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: 我的问题:

  1. Is this a real syntactic error? 这是一个真正的语法错误吗?
  2. Is there any configuration that can hide such syntactic error?. 有没有可以隐藏这种语法错误的配置?

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 . Objectint是两个步骤 - 首先需要将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.

相关问题 无法从 object 转换为 int - Cannot cast from object to int 在Java中的对象数组内初始化整数时,出现“类型不匹配:无法从int转换为Object”错误 - Getting “Type mismatch: cannot convert from int to Object” error at the time of initiation of integer inside Object Array in java 在eclipse中无法从Object转换为int - Cannot cast from Object to int in eclipse 类型不匹配:Java 代码中无法从 int 转换为 int[] 错误 - Type mismatch: cannot convert from int to int[] error in Java code 在 java 中出现错误 JSONObject 无法转换为 JSONArray? - Getting a error JSONObject cannot be cast to JSONArray in java? 获取错误 java.lang.ClassCastException: java.lang.String 无法转换为 [Ljava.lang.Object; - getting error java.lang.ClassCastException: java.lang.String cannot be cast to [Ljava.lang.Object; Getting java.lang.ClassCastException: java.lang.Integer cannot be cast to [Ljava.lang.Object Error - Getting java.lang.ClassCastException: java.lang.Integer cannot be cast to [Ljava.lang.Object Error 当我确定数据是整数时,“无法从对象转换为整数”错误 - 'Cannot cast from Object to int' error when I'm sure the data is an integer 在Java 8中无法将int强制转换为long - Cannot cast int to long in Java 8 Java-无法从HashBasedTable投射错误 <Object,Object,Object> 到表 <UUID,PotionEffectType,PotionEffect> - Java - Error Cannot cast from HashBasedTable<Object,Object,Object> to Table<UUID,PotionEffectType,PotionEffect>
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM