Do generics in Java generate all ClassCastExceptins?

Since generics are only checked at compile time using Java 5, can they exclude ClassCastExceptions in all situations?

+6
java generics classcastexception
source share
4 answers

First of all, you must make sure that your code compiles without warning. This is a good indicator. To understand why, I suggest you take a look at a sample chapter for generics from Effective Java .

Secondly, generics cannot protect you from code, for example:

public void methodOne(Integer argument) { methodTwo(argument); } public void methodTwo(Object argument) { System.out.println(((Date) argument).getTime()); } 

Thirdly, if you somehow mess with Class Loaders in one way or another, you can get weird ClassCastExceptions , for example, a thread in this discussion . It is overwhelming to see

java.lang.ClassCastException: javax.mail.Session cannot be dropped javax.mail.Session

So the answer is no, you cannot get rid of ClassCastException just by using generics.

+12
source share

The “cast-iron” guarantee that the Java 5 generator provides is that you will never see a ClassCastException exception from casts inserted by the compiler, provided that the compilation has not issued “unverified” warnings.

In real life, you often cannot avoid unverified warnings if your code uses outdated (ungendered) libraries. Throws thrown by the compiler can then throw a ClassCastException, and your task is to prevent this by ensuring that the values ​​returned by the library code are well typed for your declarations.

Otherwise, the situation will not change. Outside of generics, if you use an incompatible type, you will get a ClassCastException just like always.

(Good recommendation for this and other questions about Java Generics and Collections generics.)

+16
source share

Not. Using Java type 5.0 and generics does not make you proof of a ClassCastException.

+2
source share

Nope. generics saves you from compile-time errors, not runtime exceptions.

-one
source share

All Articles