Wednesday, December 30, 2015

Is it possible to instantiate an object from a generic parameter in Java?


The reason I’m posting this is because this question has been asked many, many, many times… and a few more.
And the answer is usually this:
You'll need an instance of the class. The generic type T isn't enough. So you'll do:
class Server <T extends RequestHandler> {
    Class<T> clazz;
    public Server(Class<T> clazz) {
        this.clazz = clazz;

    private T newRequest() {
        return clazz.newInstance();
Which lacks the straght no. While the answer above may lead a reader such as myself to believe that you can work around and use Class<T>, this is wrong. Class<T> is a type declaration, but you’ll still need a instance of it to be able to call newInstance.
Now, in c# is rather trivial to do:

class Foo<T> where T : new
{    private T getInstance()
        return Activator.CreateInstance(typeof(T));
And, as my long time readers¹ will know, I’m a C# guy. And being that, I expected to be able to do the same in Java. Now, why isn’t it possible? See, Java doesn’t really have generics… It’s implementation of generics is all done in the compiler instead of in the JVM. And this being the case, generic type information isn’t compiled to bytecode (the only answer in StackOverflow I found mentioned it was this one), and exists only during compile time. This is called Type Erasure. Now, Oracle sells it as a good thing (I disagree, of course).

1. As is “nobody”.