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

instanceof is an operator that compares an object’s instance to a type. It’s also called a type comparison operator.
In this tutorial, we’ll look at different alternatives to the traditional instanceof approach. We may need alternatives to improve code design and readability.

2. Example Setup

Let’s develop a simple program, Dinosaur and Species. This program will have a parent class and two child classes, i.e., the child classes will extend the parent class.
First, let’s create the parent class:

public class Dinosaur {
}

Next, let’s create the first child class:

public class Anatotitan extends Dinosaur {
    String run() {
        return "running";
    }
}

Finally, let’s create the second child class:

public class Euraptor extends Dinosaur {	
    String flies() {
        return "flying";
    }
}

The Dinosaur class has other methods common to the subclasses, but we’re skipping them for simplicity.
Next, let’s write a method to create new instances of our objects and invoke their movement. We’ll use instanceof to check our new instance type before returning a result:

public static void moveDinosaur(Dinosaur dinosaur) {
    if (dinosaur instanceof Anatotitan) {
        Anatotitan anatotitan = (Anatotitan) dinosaur;
        anatotitan.run();
    } 
    else if (dinosaur instanceof Euraptor) {
        Euraptor euraptor = (Euraptor) dinosaur;
        euraptor.flies();
    }
}

In the next sections, we’ll apply different alternatives.

3. Using getClass()

The getClass() method helps to get the class of an object. We can use the getClass() as an alternative to instanceof when checking whether an object belongs to a particular class or not.
In our example setup, let’s maintain the structure of our parent class and the subclasses. Then, let’s write a test method for this approach. We’ll use getClass() instead of instanceof:

public static String moveDinosaurUsingGetClass(Dinosaur dinosaur) {
    if (dinosaur.getClass().equals(Anatotitan.class)) {
        Anatotitan anatotitan = (Anatotitan) dinosaur;
        return anatotitan.run();
    } else if (dinosaur.getClass().equals(Euraptor.class)) {
        Euraptor euraptor = (Euraptor) dinosaur;
        return euraptor.flies();
    }
    return "";
}

Let’s proceed to write a unit test for this approach:

@Test
public void givenADinosaurSpecie_whenUsingGetClass_thenGetMovementOfEuraptor() {
    assertEquals("flying", moveDinosaurUsingGetClass(new Euraptor()));
}

This alternative maintains our original domain objects. What changes is the use of getClass().

4. Using Polymorphism

The concept of polymorphism makes a subclass override a method from the parent class. We can use this concept to change our example setup and improve our code design and readability.
Since we know all dinosaur move, we can change our design by introducing a move() method in our parent class:

public class Dinosaur {	
    String move() {
        return "walking";
    } 
}

Next, let’s modify our subclasses by overriding the move() method:

public class Anatotitan extends Dinosaur {
    @Override
    String move() {
        return "running";
    }
}
public class Euraptor extends Dinosaur {
    @Override
    String move() {
        return "flying";
    }
}

Now we can reference the subclasses without using the instanceof approach. Let’s write a method that accepts our parent class as an argument. We’ll return our dinosaur movement based on its specie:

public static String moveDinosaurUsingPolymorphism(Dinosaur dinosaur) { 
    return dinosaur.move(); 
}

Let’s write a unit test for this approach:

@Test 
public void givenADinosaurSpecie_whenUsingPolymorphism_thenGetMovementOfAnatotitan() { 
    assertEquals("running", moveDinosaurUsingPolymorphism(new Anatotitan()));
}

When possible, it’s recommended to change our design itself using this approach. The use of instanceof is often an indication that our design violates the Liskov Substitution Principle (LSP).

5. Using an Enumeration

In enum types, variables can be defined as sets of predefined constants. We can use this approach to improve our simple program.
First, let’s create an enum with constants that have methods. The methods of the constants override an abstract method in the enum:

public enum DinosaurEnum {
    Anatotitan {
        @Override
        public String move() {
            return "running";
        }
    },
    Euraptor {
        @Override
        public String move() {
            return "flying";
        }
    };
    abstract String move();
}

The enum constants act like subclasses used in other alternatives.
Next, let’s modify our moveDinosaur() method to use the enum type:

public static String moveDinosaurUsingEnum(DinosaurEnum dinosaurEnum) {
    return dinosaurEnum.move();
}

Finally, let’s write a unit test for this approach:

@Test
public void givenADinosaurSpecie_whenUsingEnum_thenGetMovementOfEuraptor() {
    assertEquals("flying", moveDinosaurUsingEnum(DinosaurEnum.Euraptor));
}

This design made us eliminate the parent class and the subclasses. This approach is not recommended in a complex scenario where the parent class will have more behavior than our example setup.

6. Using Visitor Pattern

The Visitor pattern helps to operate on similar/related objects. It moves the logic from the object class to another class.
Let’s apply this approach to our example setup. First, let’s create an interface with a method and pass a Visitor as an argument. This will help to retrieve the type of our object:

public interface Dinosaur {
    String move(Visitor visitor);
}

Next, let’s create a Visitor interface with two methods. The methods accepts our subclass as an argument:

public interface Visitor {
    String visit(Anatotitan anatotitan);
    String visit(Euraptor euraptor);
}

Next, let’s make our subclasses implement the Dinosaur interface and override its method. The method has Visitor as an argument to retrieve our object type. This method replaces the use of instanceof:

public class Anatotitan implements Dinosaur {
    public String run() {
        return "running";
    }
    @Override
    public String move(Visitor dinoMove) {
        return dinoMove.visit(this);
    }
}

Next, let’s create a class to implement our Visitor interface and override the methods:

public class DinoVisitorImpl implements Visitor {
    @Override
    public String visit(Anatotitan anatotitan) {
        return anatotitan.run();
    }
    @Override
    public String visit(Euraptor euraptor) {
        return euraptor.flies();
    }
}

Finally, let’s write a test method for this approach:

public static String moveDinosaurUsingVisitorPattern(Dinosaur dinosaur) {
    Visitor visitor = new DinoVisitorImpl();
    return dinosaur.move(visitor);
}

Let’s write a unit test for this approach:

@Test
public void givenADinosaurSpecie_whenUsingVisitorPattern_thenGetMovementOfAnatotitan() {
    assertEquals("running", moveDinosaurUsingVisitorPattern(new Anatotitan()));
}

This approach made use of an interface. The Visitor contains our program logic.

7. Conclusion

In this article, we’ve examined different instanceof alternatives. The instanceof approach potentially violates the Liskov Substitution Principle. Adopting alternatives gave us a better and more solid design. The polymorphism approach is recommended as it adds more value.

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)