Set the T template type at runtime passing a variable

Viewed 595

Is there way to pass a Class variable when instanciating a new template class named TemplateClass or is it absolutely a non-sens ?

Example of something i would like to do but that do not compile:

final List<TemplateClass> fields = new ArrayList<>();

public void loadDataFields() {
    for(Field x : ClassA.class.getDeclaredFields()) {
        fields.add(new TemplateClass<x.getClass()>());
    }
}

Edit

Here is the TemplateClass :

public class TemplateClass<T extends Comparable> {
    int count;
    T min;
    T max; 
}
3 Answers

In Java generics are evaluated as (mostly) compile time information due to Type Erasure.

Line new TemplateClass<x.getClass()>() makes no sense as x.getClass() is only evaluated in runtime. This line would result in compilation error.

In short - No.

There is no way it instantiates a template with dynamic class in runtime. That is because templates are evaluated at build time.

You can not assign a Type as a generic class at run time.

Generics can be used only at compile time.

Related