Do Java generics avoid all ClassCastExceptins?


Since generics are only checked during compile time with Java 5, can they avoid ClassCastExceptions in all situations?

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)  {

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 ClassCastExceptions just by properly using generics.