Search code examples
javatemplatesclassgenerics

How to use Class<T> in Java?


There's a good discussion of Generics and what they really do behind the scenes over at this question, so we all know that Vector<int[]> is a vector of integer arrays, and HashTable<String, Person> is a table of whose keys are strings and values Persons. However, what stumps me is the usage of Class<>.

The java class Class is supposed to also take a template name, (or so I'm being told by the yellow underline in eclipse). I don't understand what I should put in there. The whole point of the Class object is when you don't fully have the information about an object, for reflection and such. Why does it make me specify which class the Class object will hold? I clearly don't know, or I wouldn't be using the Class object, I would use the specific one.


Solution

  • Using the generified version of class Class allows you, among other things, to write things like

    Class<? extends Collection> someCollectionClass = someMethod();
    

    and then you can be sure that the Class object you receive extends Collection, and an instance of this class will be (at least) a Collection.