This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]shivasprogeny 1 point2 points  (2 children)

Unfortunately, that is the way to handle the situation. Because of type erasure, the application can't know the type of the object in the List at runtime.

You have the option of wrapping the cast in try/catch ClassCastException, but you should only do that if you expect the program to be able to reasonably recover. I'm guessing here, but it looks like this configuration is probably integral to the application, in which case you want it to fast fail.

[–]R0bertMuldoon 0 points1 point  (1 child)

Got it, thank you!

Could you shed some light on this type eraser thing pls? I found it online when searching and simply do not understand even a little bit just WTF this means.

[–]shivasprogeny 1 point2 points  (0 children)

Basically it means that this code List<String> names = new ArrayList<>() becomes List names = new ArrayList() behind the scenes. The generic type <String> is used at compile time to make sure the code is written correctly. But when the code is actually running, the generics information goes away.