Finding the specific type held in an ArrayList<Object> (ie. Object = String, etc.)

前端 未结 2 1122
攒了一身酷
攒了一身酷 2021-01-23 13:45

Say I have an ArrayList that I have cast to an ArrayList of objects. I know that all the objects that were in the ArrayList I cast were of the same type, but not what the type w

2条回答
  •  无人共我
    2021-01-23 14:08

    As Jeffrey mentioned, this is impossible due to magics of type erasure. Your best choice I guess is to add an additional case for the empty list:

        if (list.isEmpty()) {
            // process empty ...
        } else {
            Object o = list.get(0);
            if (o instanceof Integer) {
                List integers = (List) list;
                // process Integer ...
            } else if (o instanceof String) {
                List strings = (List) list;
                // process String ...
            } // etc...  
        }
    

    But beware! This instanceof chain is not generally considered good OO practice. Rather than passing around bare lists and then trying to guess their constituent types consider creating a wrapper class for the lists which may also hold a reference to a Class object. That way you may also be able to refactor your different processing algorithms as overriding a single process() method...

提交回复
热议问题