简体   繁体   中英

What is the meaning of the type safety warning in certain Java generics casts?

What is the meaning of the Java warning ?

Type safety: The cast from Object to List<Integer> is actually checking against the erased type List

I get this warning when I try to cast an Object to a type with generic information, such as in the following code:

Object object = getMyList();
List<Integer> list = (List<Integer>) object;

This warning is there because Java is not actually storing type information at run-time in an object that uses generics. Thus, if object is actually a List<String> , there will be no ClassCastException at run-time except until an item is accessed from the list that doesn't match the generic type defined in the variable.

This can cause further complications if items are added to the list, with this incorrect generic type information. Any code still holding a reference to the list but with the correct generic type information will now have an inconsistent list.

To remove the warning, try:

List<?> list = (List<?>) object;

However, note that you will not be able to use certain methods such as add because the compiler doesn't know if you are trying to add an object of incorrect type. The above will work in a lot of situations, but if you have to use add, or some similarly restricted method, you will just have to suffer the yellow underline in Eclipse (or a SuppressWarning annotation).

What is the meaning of the Java warning ?

Type safety: The cast from Object to List<Integer> is actually checking against the erased type List

I get this warning when I try to cast an Object to a type with generic information, such as in the following code:

Object object = getMyList();
List<Integer> list = (List<Integer>) object;

Sometimes, when we compile our Java source files, we see “unchecked cast” warning messages printed by the Java compiler.

In this tutorial, we're going to take a closer look at the warning message. We'll discuss what this warning means, why we're warned, and how to solve the problem.

Some Java compilers suppress unchecked warnings by default.

Let's make sure we've enabled the compiler's option to print “unchecked” warnings before we look into this “unchecked cast” warning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM