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

前端 未结 2 1116
攒了一身酷
攒了一身酷 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

    Nope, type erasure makes sure of that.

    0 讨论(0)
  • 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<Integer> integers = (List<Integer>) list;
                // process Integer ...
            } else if (o instanceof String) {
                List<String> strings = (List<String>) 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...

    0 讨论(0)
提交回复
热议问题