2

If I have a generic class like this:

class SomeClass<T> { 
  public aFunction(T anArg) {
    // some implementation
  }
}

Is there then a way to instantiate the SomeClass, using a variable of the Class type?

I basically want to be able to do this:

Class var = String.class; // just an example, obviously
SomeClass<?> anInstance = new SomeClass< var >();

Or is there a workaround?

Erik
  • 3,598
  • 14
  • 29

2 Answers2

1

Java uses type erasure, so at runtime generic types are not aware of their type parameters. So the simple answer is "no".

Depending on your needs, you could either use one of the Class.newInstance methods, or keep the class object in a field.

Michael Bar-Sinai
  • 2,729
  • 20
  • 27
1

From a purely syntactic point of view, no, you can't. Type arguments must be type names (or the wildcard, ?) known at compile time. They cannot be variables or other expressions that evaluate to a value.

It is still unclear why you need this, especially since your anInstance is of type SomeClass<?>, in which case you wouldn't care about the type argument used.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724