How to cast List<Object> to List<MyClass>

user198313 picture user198313 · Dec 16, 2009 · Viewed 205.1k times · Source

This does not compile, any suggestion appreciated.

 ...
  List<Object> list = getList();
  return (List<Customer>) list;

Compiler says: cannot cast List<Object> to List<Customer>

Answer

irreputable picture irreputable · Dec 17, 2009

you can always cast any object to any type by up-casting it to Object first. in your case:

(List<Customer>)(Object)list; 

you must be sure that at runtime the list contains nothing but Customer objects.

Critics say that such casting indicates something wrong with your code; you should be able to tweak your type declarations to avoid it. But Java generics is too complicated, and it is not perfect. Sometimes you just don't know if there is a pretty solution to satisfy the compiler, even though you know very well the runtime types and you know what you are trying to do is safe. In that case, just do the crude casting as needed, so you can leave work for home.