What you're trying to do fundamentally doesn't work in Java. Actually, it's much easier than what you're trying to do (in some ways). Due to type erasure as pointed out by @ElliottFrisch, at runtime, you eliminate the generic type. The generic is only used by compiler to make sure that you don't add an object to a List
, for instance, that you're not expecting. At runtime this:
List<String> strings = new ArrayList<String>();
becomes
List strings = new ArrayList();
Because the compiler knew about it when it compiled it, you can be assured that, unless you do something crazy with reflection or the like, every object in the list will be a String
. No class exists for ArrayList<String>
, only ArrayList
. The generic collections operate only on Objects
and the compiler provides the casting when necessary.
TL;DR: Generics are only in place to help you at compile time. Because you're using reflection to deserialize objects, you won't have that anyway (really, typesafety is a compile time construct as well, you can attempt to call any method on any object, it just won't work unless it's implemented). Your code will be responsible for creating the objects that will be added to the generic container and ensuring that all of the objects are of the expected type.