Do generics in Java avoid all classcastexceptions?

Because generics are only checked during compilation using Java 5, they can avoid using classcastexceptions

Solution

First, you should make sure that your code compiles without unsent error warnings This is a good indicator To understand why, I suggest you take a look at the sample chapter for genetics from effective Java

Second, generics cannot protect you from the following code:

public void methodOne(Integer argument)  {
     methodTwo(argument);
} 

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

Third, if you mess up the classloader in some way, you may encounter strange classcastexceptions, such as this discussion thread It looks troublesome

So the answer is no, you can only get rid of classcastexceptions by using generics correctly

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>