[英]ClassCastException when casting to object array
I am getting this runtime error: 我收到此运行时错误:
Exception in thread "main" java.lang.ClassCastException: Employee cannot be cast to [LEmployee;
It is coming from this line of code, where I am casting the file contents to Employee[] 它来自这一行代码,在这里我将文件内容转换为Employee []
Employee[] EmpArray;
EmpArray = (Employee[]) objectIn.readObject();
What is confusing me is the "[L" in the error. 使我感到困惑的是错误中的“ [L””。 I have no idea where that came from.
我不知道那是哪里来的。
[L
in Java
means "one-dimensional array of objects of the class, the fully qualified name of which immediately follows, until (and excluding) the ;
symbol" (eg, [Ljava.lang.String;
denotes a String[]
array). [L
Java
[L
表示“该类的一维对象数组,其全限定名紧随其后,直到(并排除) ;
符号为止”(例如[Ljava.lang.String;
表示String[]
数组)。 More details can be found in a related question on StackOverflow
. 有关更多详细信息,请参见
StackOverflow
上的相关问题 。
Without more details, one can only speculate as to the cause of the ClassCastException
. 没有更多细节,人们只能推测
ClassCastException
的原因。
Apparently you are trying to deserialize an Employee[]
array from an ObjectInputStream
, which actually reads from a serialized Employee
(not Employee[]
) object. 显然,您正在尝试从
ObjectInputStream
反序列化Employee[]
数组,该数组实际上是从序列化的Employee
(不是Employee[]
)对象读取的。
The issue may be in the serialization logic. 问题可能出在序列化逻辑中。
To check whether this is the case, just cast the readObject()
call to Employee
, not Employee[]
, and see if that works. 要检查是否存在这种情况,只需将
readObject()
调用readObject()
为Employee
,而不是Employee[]
,然后看是否可行。
A quite good read explaining bytecode (and more) can be found here: http://www.cubrid.org/blog/dev-platform/understanding-jvm-internals/ - see table 1 for bytecode type expressions. 可以在这里找到解释字节码(以及更多内容)的很好的读物: http : //www.cubrid.org/blog/dev-platform/understanding-jvm-internals/-有关字节码类型表达式,请参见表1。
Interesting in your case are (Java Bytecode - Type - Description): 您的情况很有趣(Java字节码-类型-描述):
Minor nitpick: your variable EmpArray
doesn't follow Java naming convention since it starts with capital letter. 次要nitpick:变量
EmpArray
不遵循Java命名约定,因为它以大写字母开头。 Reference: http://www.javapractices.com/topic/TopicAction.do?Id=58 参考: http : //www.javapractices.com/topic/TopicAction.do? Id= 58
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.