Brennan Hoeting
Brennan Hoeting

Reputation: 1213

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[] EmpArray;
EmpArray = (Employee[]) objectIn.readObject();

What is confusing me is the "[L" in the error. I have no idea where that came from.

Upvotes: 0

Views: 339

Answers (2)

PNS
PNS

Reputation: 19905

[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" (e.g., [Ljava.lang.String; denotes a String[] array). More details can be found in a related question on StackOverflow.

Without more details, one can only speculate as to the cause of the ClassCastException.

Apparently you are trying to deserialize an Employee[] array from an ObjectInputStream, which actually reads from a serialized Employee (not Employee[]) object.

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.

Upvotes: 2

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.

Interesting in your case are (Java Bytecode - Type - Description):

  • L - reference - an instance of class
  • [ - reference - one array dimension

Minor nitpick: your variable EmpArray doesn't follow Java naming convention since it starts with capital letter. Reference: http://www.javapractices.com/topic/TopicAction.do?Id=58

Upvotes: 2

Related Questions