Java Generics – How to Instantiate Generic Types

genericsjava

I would like to create an object of Generics Type in java. Please suggest how can I achieve the same.

Note: This may seem a trivial Generics Problem. But I bet.. it isn't. 🙂

suppose I have the class declaration as:

public class Abc<T> {
    public T getInstanceOfT() {
       // I want to create an instance of T and return the same.
    }
}

Best Answer

public class Abc<T> {
    public T getInstanceOfT(Class<T> aClass) {
       return aClass.newInstance();
    }
}

You'll have to add exception handling.

You have to pass the actual type at runtime, since it is not part of the byte code after compilation, so there is no way to know it without explicitly providing it.

Related Question