Exception occurred during event dispatching:java.lang.ClassCastException in a JRE 1.4 Environment

97 Views Asked by At

I've been receiving ClassCastException in my code. Objective initially was to convert Set to List since the refreshDetailVOTable method will only get Set. The problem could have been in converting Set to List. refreshDetailVOTable might took the wrong List that's why I'm receiving ClassCastException.

Upon investigation, it was found out that:

I’ve been using all raw types. I should use generics instead. They will help find this kind of error at compile time.

The method is receiving a parameter List detailIRsToDelete from which I got an iterator and iterate over the elements like so:

         for (Iterator iDetails = detailIRsToDelete.iterator(); iDetails.hasNext();) {
             IdentifiableReference detailIR = (IdentifiableReference) iDetails.next();

I might have accidentally put something other than an IdentifiableReference into detailIRsToDelete, thus getting a ClassCastException in the assignment statement within the loop.

The list parameter should then be declared as:

List <IdentifiableReference> detailIRsToDelete

The act of putting things into this list would be checked by the compiler, and the error would occur at the point where the erroneous object was added, at compile time, instead of later at runtime as experienced.

Issue: This then should solve the Class Cast Exception, however, this could not be applied in the current JRE which is 1.4

Do we have any workaround for JRE 1.4 aside from upgrading?

1

There are 1 best solutions below

1
On

you can use instanceof before trying to cast

Object o = iDetails.next();
if(o instanceof IdentifiableReference)
  IdentifiableReference detailIR = (IdentifiableReference)o;