1. Overview

Generics provide an elegant way to introduce an additional layer of abstraction in our codebase while promoting code reusability and enhancing code quality.

When working with generic data types, sometimes we’d like to create new instances of them. However, we may encounter different challenges because of how generics are designed in Java.

In this tutorial, we’ll first analyze why instantiating a generic type isn’t as straightforward as instantiating a class. Then, we’ll explore several ways to create an instance of it.

2. Understanding Type Erasure

Before we start, we should be aware that generic types behave differently at compile time and runtime.

Due to the technique called type erasure, the generic type isn’t preserved at runtime. Simply put, type erasure is the process of requiring the generic type at compile time and discarding this information at runtime. The compiler removes all information related to the type parameter and type arguments from generic classes and methods.

Moreover, type erasure enables Java applications that use generics to maintain backward compatibility with libraries created before generics were introduced.

Having the above in mind, we can’t use the new keyword followed by the constructor to create an object of the generic type:

public class GenericClass<T> {
    private T t;

    public GenericClass() {
        this.t = new T(); // DOES NOT COMPILE
    }
}

Since generics are a compile-time concept and information is erased at runtime, generating the bytecode for new T() would be impossible because T is an unknown type.

Furthermore, the generic type is replaced with the first bound or with the Object class if the bound isn’t set. The T type from our example doesn’t have bounds, so Java treats it as an Object type.

3. Example Setup

Let’s set up the example we’ll use throughout this tutorial. We’ll create a simple service for sending messages.

First, let’s define the Sender interface with the send() method:

public interface Sender {
    String send();
}

Next, let’s create a concrete Sender implementation for sending emails:

public class EmailSender implements Sender {
    private String message;

    @Override
    public String send() {
        return "EMAIL";
    }
}

Then, we’ll create another implementation for sending notifications, but it’ll be a generic class itself:

public class NotificationSender<T> implements Sender {
    private T body;

    @Override
    public String send() {
        return "NOTIFICATION";
    }
}

Now that we’re all set, let’s explore different ways to create an instance of a generic type.

4. Using Reflection

One of the most common approaches to instantiating a generic type is through plain Java and reflection.

To create an instance of a generic type, we need to know at least the type of the object we want to make.

Let’s define a SenderServiceReflection generic class that will be responsible for creating instances of different services:

public class SenderServiceReflection<T extends Sender> {
    private Class<T> clazz;

    public SenderServiceReflection(Class<T> clazz) {
        this.clazz = clazz;
    }

}

We defined the instance variable of Class, where we’ll store information about the type of class we want to instantiate.

Next, let’s create a method responsible for creating an instance of a class:

public T createInstance() {
    try {
        return clazz.getDeclaredConstructor().newInstance();
    } catch (Exception e) {
        throw new RuntimeException("Error while creating an instance.");
    }
}

Here, we called the getDeclaredConstructor().newInstance() to instantiate a new object. Moreover, the actual type should have a no-argument constructor for the above code to work.

Additionally, it’s worth noting that calling the newInstance() method on the Class directly has been deprecated since Java 9.

Next, let’s test our method:

@Test
void givenEmailSender_whenCreateInstanceUsingReflection_thenReturnResult() {
    SenderServiceReflection<EmailSender> service = new SenderServiceReflection<>(EmailSender.class);

    Sender emailSender = service.createInstance();
    String result = emailSender.send();

    assertEquals("EMAIL", result);
}

However, using Java reflection has its limitations. For example, our solution won’t work if we try to instantiate the NotificationSender class:

SenderServiceReflection<NotificationSender<String>> service = new SenderServiceReflection<>(NotificationSender<String>.class);

If we try to pass the NotificationSender.class to the constructor, we’ll get a compile error:

Cannot select from parameterized type

5. Using the Supplier Interface

Java 8 brought a convenient way to create an instance of a generic type by utilizing the Supplier functional interface:

public class SenderServiceSupplier<T extends Sender> {
    private Supplier<T> supplier;

    public SenderServiceSupplier(Supplier<T> supplier) {
        this.supplier = supplier;
    }

    public T createInstance() {
        return supplier.get();
    }
}

Here, we defined the Supplier instance variable, which is set through the constructor’s parameter. To retrieve the generic instance, we called its single get() method.

Let’s create a new instance using a method reference:

@Test
void givenEmailSender_whenCreateInstanceUsingSupplier_thenReturnResult() {
    SenderServiceSupplier<EmailSender> service = new SenderServiceSupplier<>(EmailSender::new);

    Sender emailSender = service.createInstance();
    String result = emailSender.send();

    assertEquals("EMAIL", result);
}

Additionally, if the constructor of an actual type T takes arguments, we can use lambda expression instead:

@Test
void givenEmailSenderWithCustomConstructor_whenCreateInstanceUsingSupplier_thenReturnResult() {
    SenderServiceSupplier<EmailSender> service = new SenderServiceSupplier<>(() -> new EmailSender("Baeldung"));

    Sender emailSender = service.createInstance();
    String result = emailSender.send();

    assertEquals("EMAIL", result);
}

What’s more, this approach works without any issues when we use the nested generic class:

@Test
void givenNotificationSender_whenCreateInstanceUsingSupplier_thenReturnCorrectResult() {
    SenderServiceSupplier<NotificationSender<String>> service = new SenderServiceSupplier<>(
      NotificationSender::new);

    Sender notificationSender = service.createInstance();
    String result = notificationSender.send();

    assertEquals("NOTIFICATION", result);
}

6. Using the Factory Design Pattern

Similarly, instead of using the Supplier interface, we can utilize the factory design pattern to accomplish the same behavior.

Firstly, let’s define the Factory interface that will substitute the Supplier interface:

public interface Factory<T> {
    T create();
}

Secondly, let’s create a generic class that takes Factory as a constructor argument:

public class SenderServiceFactory<T extends Sender> {
    private final Factory<T> factory;

    public SenderServiceFactory(Factory<T> factory) {
        this.factory = factory;
    }

    public T createInstance() {
        return factory.create();
    }
}

Next, let’s create a test to check whether the code works as expected:

@Test
void givenEmailSender_whenCreateInstanceUsingFactory_thenReturnResult() {
    SenderServiceFactory<EmailSender> service = new SenderServiceFactory<>(EmailSender::new);

    Sender emailSender = service.createInstance();
    String result = emailSender.send();

    assertEquals("EMAIL", result);
}

Additionally, instantiating the NotificationSender works without any issues:

@Test
void givenNotificationSender_whenCreateInstanceUsingFactory_thenReturnResult() {
    SenderServiceFactory<NotificationSender<String>> service = new SenderServiceFactory<>(
      () -> new NotificationSender<>("Hello from Baeldung"));

    NotificationSender<String> notificationSender = service.createInstance();
    String result = notificationSender.send();

    assertEquals("NOTIFICATION", result);
    assertEquals("Hello from Baeldung", notificationSender.getBody());
}

7. Using Guava

Lastly, let’s look at how to do this with the Guava library.

Guava provides the TypeToken class, which uses reflection to store generic information that will be available at runtime. It also offers additional utility methods for manipulating generic types.

Let’s create the SenderServiceGuava class with TypeToken as an instance variable:

public class SenderServiceGuava<T extends Sender> {
    TypeToken<T> typeToken;

    public SenderServiceGuava(Class<T> clazz) {
        this.typeToken = TypeToken.of(clazz);
    }

    public T createInstance() {
        try {
            return (T) typeToken.getRawType().getDeclaredConstructor().newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

To create an instance, we called the getRawType(), which returns a runtime class type.

Let’s test our example:

@Test
void givenEmailSender_whenCreateInstanceUsingGuava_thenReturnResult() {
    SenderServiceGuava<EmailSender> service = new SenderServiceGuava<>(EmailSender.class);

    Sender emailSender = service.createInstance();
    String result = emailSender.send();

    assertEquals("EMAIL", result);
}

Alternatively, we can define the TypeToken as an anonymous class to store the information of the generic type:

TypeToken<T> typeTokenAnonymous = new TypeToken<T>(getClass()) {
};

public T createInstanceAnonymous() {
    try {
        return (T) typeTokenAnonymous.getRawType().getDeclaredConstructor().newInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

Using this approach, we can create the SenderServiceGuava as an anonymous class as well:

@Test
void givenEmailSender_whenCreateInstanceUsingGuavaAndAnonymous_thenReturnResult() {
    SenderServiceGuava<EmailSender> service = new SenderServiceGuava<EmailSender>() {
    };

    Sender emailSender = service.createInstanceAnonymous();
    String result = emailSender.send();

    assertEquals("EMAIL", result);
}

The solution above works well if a generic class itself has a type parameter:

@Test
void givenNotificationSender_whenCreateInstanceUsingGuavaAndAnonymous_thenReturnResult() {
    SenderServiceGuava<NotificationSender<String>> service = new SenderServiceGuava<NotificationSender<String>>() {
    };

    Sender notificationSender = service.createInstanceAnonymous();
    String result = notificationSender.send();

    assertEquals("NOTIFICATION", result);
}

8. Conclusion

In this article, we learned how to create an instance of a generic type in Java.

To summarize, we examined why we cannot create instances of a generic type using the new keyword. Additionally, we explored how to create an instance of a generic type using reflection, the Supplier interface, the factory design pattern, and, lastly, the Guava library.

As always, the entire source code is available over on GitHub.