views:

524

answers:

4

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

+2  A: 

No. Using Java 5.0 and generics type doesn't make you ClassCastException-proof.

Grzegorz Oledzki
is there any way for that...
cdb
If you don't cast at all, you shouldn't see any ClassCastException.
Grzegorz Oledzki
+12  A: 

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

Robert Munteanu
+1 For the ClassLoader gotchas
mtpettyp
+16  A: 

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

mauricen
A: 

Nope. generics only save you from compile time errors, not runtime exceptions.

Nick
-1: What is a compile time exception?
Stephen C