How can I use the cast method of a generics vector. What I thought of, is patterns like (Vector<T>).class.cast(getDates());
or (Vector<a_typeClass>).class.cast(getDates());
but they are not working. A workarround is to cycle trough all elements. But there has to be a way to use cast for a generics Vector.
(Yes, I have to use Vector, because I'm extending an API)
Edit: This is only a small part of a much more complex code. The cast will never fail because of types checking: if (Date.class.isAssignableFrom(a_typeClass))
. I also left out the null
check in the sample. Eclipse is raising an error Type mismatch: cannot convert from Vector<Date> to Vector<T>
because it is not recognizing the type check pattern.
Edit: In the samples I used isAssignableFrom the other way. Was before Date.class.isAssignableFrom(a_typeClass)
is now a_typeClass.equals(Date.class)
. But still I have to use the (Vector<T>)
cast, if I don't use it, compile error Type mismatch: cannot convert from Vector<Date> to Vector<T>
will be raised. Thanks to davmac and JB Nizet.
Sample:
public class VectorCast {
@SuppressWarnings("unchecked")
public <T> Vector<T> getVector1(Class<T> a_typeClass) {
Vector<T> returnValues = new Vector<>();
if (a_typeClass.equals(Date.class)) {
returnValues = (Vector<T>) getDates();
// Not working
// return (Vector<T>).class.cast(getDates());
// return (Vector<a_typeClass>).class.cast(getDates());
}
return returnValues;
}
public Vector<Date> getDates() {
// Just dummy Values
return new Vector<Date>(Arrays.asList(new Date(0), new Date()));
}
public static void main(String[] args) {
VectorCast vectorCast = new VectorCast();
System.out.println(vectorCast.getVector1(Date.class));
}
}
Work around Sample:
public <T> Vector<T> getVector2(Class<T> a_typeClass) {
Vector<T> returnValues = new Vector<>();
if (a_typeClass.equals(Date.class)) {
for (Date date : getDates()) {
returnValues.add(a_typeClass.cast(date));
}
}
return returnValues;
}