I want to implement the following function:
public boolean checkType(Vector<?> vec)
{
// return true if its Vector<Integer> and false otherwise
}
How can I check the vector elements type ?
Note that the vector might be empty thus I can’t check if the first element is “instanceof” Integer or String …
EDIT:
Well, I had something in mind I don’t know if it will work or not
Can I implement the checkType function as following:
public <T> boolean checkType(Vector<T> vec)
{
// return true if T is Integer and false otherwise
}
is it possible to check if T is Integer ?!
Thanks in Advance
Generic type parameters are unrecoverable (except for some special cases) at runtime because of type erasure. This means that at runtime, both
Vector<Integer>andVector<String>are simply justVectors and their elements are justObjectreferences.Only the actual runtime classes (discoverable by
instanceofchecks as you pointed out) of the individual elements make the notion of the element type, otherwise the Vector itself has no idea what it’s element type is.So basically, an empty vector of any type is equal to empty vector of any other type. It is even safe to cast it like this:
However there is one problem, because although you can say that empty vector conforms to any required element type, this statement stands only as long as the vector stays empty. Because if you do this:
EDIT:
To answer you second question: No it isn’t possible to write anything like this:
However you can write a method that uses a class token as an input parameter:
And then you can use it like this: