Since generics are only checked during compile time with Java 5, can they avoid ClassCastExceptions in all situations?
No. Using Java 5.0 and generics type doesn't make you ClassCastException-proof.
First of all, you should make sure that your code compiles without unckeched warnings. That is a good indicator. To understand why, I suggest you take a look at the sample chapter for generics from Effective Java.
Second of all, generics can't guard you from code such as:
public void methodOne(Integer argument) {
methodTwo(argument);
}
public void methodTwo(Object argument) {
System.out.println(((Date) argument).getTime());
}
Third of all, if you're in some way or another messing with Class Loaders, you might get strange ClassCastExceptions
, such as in this discussion thread. It is mind-numbing to see
java.lang.ClassCastException: javax.mail.Session cannot be cast to javax.mail.Session
So the answer is no, you can't get rid of ClassCastException
s just by properly using generics.
The "cast-iron" guarantee that Java 5 generics provides is that you will never see a ClassCastException from the casts inserted by the compiler provided that compilation produced no "unchecked" warnings.
In real life, you often can't avoid unchecked warnings if your code uses legacy (non-generified) libraries. Then the compiler-generated casts can throw ClassCastException, and it's your job to prevent this by ensuring that the values returned by library code are well-typed for your declarations.
Otherwise the situation is unchanged. Outside of generics, if you cast to an incompatible type you'll get a ClassCastException the same way as you always did.
(A good reference for this and other generics questions is Java Generics and Collections.)