This came up as a question I asked in an interview recently as something the candidate wished to see added to the Java language. It\'s commonly-identified as a pain that Jav
From the few times that I came across this "need", it ultimately boils down to this construct:
public class Foo {
private T t;
public Foo() {
this.t = new T(); // Help?
}
}
This does work in C# assuming that T
has a default constructor. You can even get the runtime type by typeof(T) and get the constructors by Type.GetConstructor().
The common Java solution would be to pass the Class
as argument.
public class Foo {
private T t;
public Foo(Class cls) throws Exception {
this.t = cls.newInstance();
}
}
(it does not necessarily need to be passed as constructor argument, as a method argument is also fine, the above is just an example, also the try-catch
is omitted for brevity)
For all other generic type constructs, the actual type can easily be resolved with a bit help of reflection. The below Q&A illustrate the use cases and possibilities: