Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java dynamic return type?

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.

like image 232
NaN Avatar asked Oct 14 '12 11:10

NaN


2 Answers

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;
}
like image 91
Sergey Kalinichenko Avatar answered Sep 28 '22 04:09

Sergey Kalinichenko


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.

like image 21
Marko Topolnik Avatar answered Sep 28 '22 02:09

Marko Topolnik