eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

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<T>, 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<T> 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<String>.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<T> 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<T> 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<T> 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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments