How to cast List<Object> to List

后端 未结 16 965
时光取名叫无心
时光取名叫无心 2020-11-27 11:43

This does not compile, any suggestion appreciated.

 ...
  List list = getList();
  return (List) list;


Compil

16条回答
  •  天涯浪人
    2020-11-27 12:17

    As others have pointed out, you cannot savely cast them, since a List isn't a List. What you could do, is to define a view on the list that does in-place type checking. Using Google Collections that would be:

    return Lists.transform(list, new Function() {
      public Customer apply(Object from) {
        if (from instanceof Customer) {
          return (Customer)from;
        }
        return null; // or throw an exception, or do something else that makes sense.
      }
    });
    

    提交回复
    热议问题