0

Here is my generic class:

class MultiType<T> {
    private T value;

    MultiType(T value) {
        this.value = value;
    }

    T get() {
        return value;
    }
}

At the moment, I can obviously invoke it with:

MultiType multi = new MultiType<Integer>(0);

Or:

MultiType multi = new MultiType<String>("Hello, World");

However, I want to know if the type can be dynamically set by a variable. I know the below doesn't work, but something along the lines of that is what I am looking for:

Class strType = "".getClass();
MultiType multi = new MultiType<strType>("Hello, World");

Thanks in advance.

1 Answers1

0

At least in Java, generics are a compile-time feature. What you want to achieve is dynamic (runtime) generics, which is thus impossible.

Timmos
  • 3,215
  • 2
  • 32
  • 40
  • This is not entirely true. Generic declarations and their type erasure can be analyzed at runtime, however, instances of generic types can not be checked for their generic type at runtime. – Sean Patrick Floyd Apr 21 '16 at 10:29