How to cast generic List types in java?

后端 未结 9 990
离开以前
离开以前 2020-12-09 17:33

Well, I have a class Customer (no base class).

I need to cast from LinkedList to List. Is there any clean way to do this?

Just so you know, I need to cast it

9条回答
  •  粉色の甜心
    2020-12-09 18:26

    If your list is of a generic type for eg

    ArrayList strList = new ArrayList(); strList.add("String1"); Object o = strList;

    then Following method should work

    public  List getListObjectInBodyOfType(Class classz, Object body) {
        if(body instanceof List){
            List tempList = (List)body;
            if(tempList.size() > 0 && tempList.get(0).getClass().equals(classz)){
                return (List) body;
            }
        }
        return new ArrayList();
    }
    

    How to use it?

    List strList1 = getListObjectInBodyOfType(String.class, o);
    

    as I mentioned before it works if the Object contains generic list, this won't work if you pass a non-generic list with mixed type of elements

提交回复
热议问题