Java Top

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

>> CHECK OUT THE COURSE

1. Overview

In this quick tutorial, we'll discuss how we can check if a class is abstract or not in Java by using the Reflection API.

2. Example Class and Interface

To demonstrate this, we'll create an AbstractExample class and an InterfaceExample interface:

public abstract class AbstractExample {

    public abstract LocalDate getLocalDate();

    public abstract LocalTime getLocalTime();
}

public interface InterfaceExample {
}

3. The Modifier#isAbstract Method

We can check if a class is abstract or not by using the Modifier#isAbstract method from the Reflection API:

@Test
void givenAbstractClass_whenCheckModifierIsAbstract_thenTrue() throws Exception {
    Class<AbstractExample> clazz = AbstractExample.class;
 
    Assertions.assertTrue(Modifier.isAbstract(clazz.getModifiers()));
}

In the example above, we first obtain the instance of the class we want to test. Once we have the class reference, we can call the Modifier#isAbstract method. As we'd expect, it returns true if the class is abstract, and otherwise, it returns false.

It's worthwhile to mention that an interface class is abstract as well. We can verify it by a test method:

@Test
void givenInterface_whenCheckModifierIsAbstract_thenTrue() {
    Class<InterfaceExample> clazz = InterfaceExample.class;
 
    Assertions.assertTrue(Modifier.isAbstract(clazz.getModifiers()));
}

If we execute the test method above, it'll pass.

The Reflection API provides an isInterface() method as well. If we want to check if a given class is abstract but not an interface, we can combine the two methods:

@Test
void givenAbstractClass_whenCheckIsAbstractClass_thenTrue() {
    Class<AbstractExample> clazz = AbstractExample.class;
    int mod = clazz.getModifiers();
 
    Assertions.assertTrue(Modifier.isAbstract(mod) && !Modifier.isInterface(mod));
}

Let's also validate that a concrete class returns the appropriate results:

@Test
void givenConcreteClass_whenCheckIsAbstractClass_thenFalse() {
    Class<Date> clazz = Date.class;
    int mod = clazz.getModifiers();
 
    Assertions.assertFalse(Modifier.isAbstract(mod) && !Modifier.isInterface(mod));
}

4. Conclusion

In this tutorial, we've seen how we can check if a class is abstract or not.

Further, we've addressed how to check if a class is an abstract class but not an interface through an example.

As always, the complete code for this example is available over on GitHub.

Java bottom

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

>> CHECK OUT THE COURSE
Junit footer banner
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Comments are closed on this article!