I want to write a function which would return me a Vector of the specified type which I pass to it. For example:
// Here getNewVector(<ClassType>) should return me an integer Vector.
Vector<Integer> myIntVector = getNewVector(Integer.class);
//should get a String vector in this case and so on.
Vector<String> myStringVector = getNewVector(String.class) ;
I want to implement getVector(Class classType) in such a way so as to return a new vector of that particular class type. How can we achieve it without using reflections and by not passing the class name as a String(I would like to pass the class type only as I had mentioned in the example above.)
Actually, I want a function getVector() somewhat like this..
Vector<T> getVector(T t) {
return new Vector<t>();
}
Take a look at the Java Tutorial for Generic Methods. Here’s one way to do what you want:
I’m assuming that you’re not going to just want to throw away the
tyou pass intogetVector(T t), so I stuck it in theVector.Theoretically, you don’t need to pass anything into the method if all you want is the typing mechanism:
Java can figure out that you want it typed as a
Vector<Integer>from the generic typing on the declaration.