JDK-5069708 : ClassCastException should have required-class and actual-class properties
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.lang
  • Affected Version: 5.0,7
  • Priority: P4
  • Status: Open
  • Resolution: Unresolved
  • OS: windows_xp
  • CPU: x86
  • Submitted: 2004-06-29
  • Updated: 2012-09-29
Related Reports
Duplicate :  
Duplicate :  
Name: rmT116609			Date: 06/29/2004

Class java.lang.ClassCastException should have properties for the type that
was required but not found and for the class that was found but was not
assignable to the required type.

ClassCastException should have a constructor that has parameters for
the required and actual types.  The default message should display both
the required type and the actual class.

Some issues to consider in detailed design:
- The typical pattern needs just the required and actual types and needs to
  display the two types (labeled enough to know which is which).
- Other patterns need to override the default behavior, when might affect
  whether the default message should be assembled in the constructor
  or in the getMessage() method.
- Typical use probably involves already-loaded classes, so the parameters
  probably should be of type java.lang.Class.  (It is possible that they should
  instead be the names of the classes, of type java.lang.String.)

The main reasons for this are to remind developers  to report the required type in the error message and to make it easy for them to report  the information.

The reason for that is to try to ensure that other developers who see a
ClassCastException from inside code for which they don't have the
source can tell what type was expected.

(Note how the typical ClassCastException message, with only the actual type, it fine when you have the source code to see the required type, but is useless when you don't have the source code.  Having the required type in the error message would be extremely helpful.

(Incident Review ID: 281795) 

I've had a similar request from Rich Berlin at Guidewire. In addition, it would be nice to include some information about the object that was cast, perhaps calling toString() on it, or even including the instance reference itself in the exception. Doing this may involve unacceptable leakage of information, however.