I have a container (List) of some elements of type T and want to filter it. So it contains only elements of a specific subtype U. Would it be possible to set a "dynamic" return type?
example:
class SomeContainer<T> extends ArrayList<T>{
public SomeContainer<T> subset(Class c){
SomeContainer<...here the type of c > output = new SomeContainer<.. also ..>();
//filter own elements and only add c-objects in the new list
return output;
}
}
At the moment it returns a list of the generic type T and not of the c-Class-type (Subtype of T). Therefore I sometimes receive the following Compiler-Notice:
Note: SomeContainer.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Because I want to filter the list after objects of a subtype and trigger subtype-specific methods I would need a specific subtype list.
java.lang.Class
is a generic type parameterized on itself, so you can use its type parameter, like this:
public <U extends T> SomeContainer<U> subset(Class<U> c){
SomeContainer<U> output = new SomeContainer<U>();
for (T val : this) {
if (c.isInstance(val)) {
output.add(c.cast(val));
}
}
return output;
}
Generics are a compile-time artefact only, therefore your scheme can't work. The compiler cannot predict what class you will want at each execution of the line of code that makes a call to this function. You cannot make this solution type-safe unless you have a very constrained, and quite useless, case where you only ever use class literals to call your function. That would, however almost certainly defeat its purpose to be, as you stated, dynamic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With