Course – LS – All

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

>> CHECK OUT THE COURSE

1. Overview

It’s often necessary to determine whether a given object is an array or not in Java. This can be useful in several different cases, such as when working with arrays in a generic manner or performing type checks in our code.

In this tutorial, we’ll explore how to implement the determination.

2. Introduction to the Problem

First of all, let’s look at two objects:

final Object ARRAY_INT = new int[] { 1, 2, 3, 4, 5 };
final Object ARRAY_PERSON = new Person[] { new Person("Jackie Chan", "Hong Kong"), new Person("Tom Hanks", "United States") };

We’ve declared two objects in the type Object. Further, both objects are arrays. One is a primitive array (int[]), and the other one is an array of Person instances (Person[]). Well, Person is a simple POJO class with two properties:

class Person {
    private String name;
    private String Location;
                                                                            
    public Person(String name, String location) {
        this.name = name;
        this.Location = location;
    }
                                                                            
    // getter methods are omitted
}

We need to find a way to determine that the two objects are arrays. Java provides simple and straightforward ways to check if an object is an array. In this tutorial, we’ll learn two different approaches:

  • using the instanceof operator
  • using the Class.isArray() method

For simplicity, we’ll use unit test assertions to verify whether each approach can give us the expected result.

Next, let’s see them in action.

3. Using the instanceof Operator

The instanceof operator in Java is used to determine the type of the given object. It takes the form obj instanceof type, where the obj is the object being checked, and type is the type being checked for.

Since we generally want to check if the object is an array, we can use Object[] as the type. For example, checking the Person array in this way works as expected:

assertTrue(ARRAY_PERSON instanceof Object[]);

However, in Java, we have primitive arrays and object arrays. For example, our ARRAY_INT is a primitive array. If we check an array of primitives using the same approach, it would fail:

assertFalse(ARRAY_INT instanceof Object[]);

The instanceof operator returns true if we check the ARRAY_INT object with the type int[]:

assertTrue(ARRAY_INT instanceof int[]);

But we don’t know if the given object is in type Object[], int[], long[], or short[]. So, given an instance obj in type Object, if we want to use the instanceof approach to check if it’s an array, we need to cover the object array and all primitive array cases:

obj instanceof Object[] || obj instanceof boolean[] ||
obj instanceof byte[] || obj instanceof short[] ||
obj instanceof char[] || obj instanceof int[] ||
obj instanceof long[] || obj instanceof float[] ||
obj instanceof double[]

The checking logic is a bit lengthy. However, we can put this check in a method:

boolean isArray(Object obj) {
    return obj instanceof Object[] || obj instanceof boolean[] || 
      obj instanceof byte[] || obj instanceof short[] || 
      obj instanceof char[] || obj instanceof int[] || 
      obj instanceof long[] || obj instanceof float[] || 
      obj instanceof double[];
}

Then, we can use our isArray() method to check both object and primitive arrays:

assertTrue(isArray(ARRAY_PERSON));
assertTrue(isArray(ARRAY_INT));

4. Using the Class.isArray() Method

We’ve learned to use the instanceof operator to determine whether a given object is an array. This approach does the job. However, the implementation looks verbose, as we need to cover all primitive array scenarios. So next, let’s see another more compact approach: using the Class.isArray() method.

The method name tells what it actually does. The Class.isArray() method belongs to the java.lang.Class class, and it returns true if the specified object is an array and false otherwise. Furthermore, the Class.isArray() method can handle both object and primitive arrays:

assertTrue(ARRAY_INT.getClass().isArray());
assertTrue(ARRAY_PERSON.getClass().isArray());

Additionally, if we need to know the type of the elements of an array, we can use the Class.getComponentType() method:

assertEquals(Person.class, ARRAY_PERSON.getClass().getComponentType());
assertEquals(int.class, ARRAY_INT.getClass().getComponentType());

Once we know the given object is an array and its elements’ type, we can retrieve the required element using the Array.get() method and cast it to the concrete type:

if (ARRAY_PERSON.getClass().isArray() && ARRAY_PERSON.getClass().getComponentType() == Person.class) {
    Person person = (Person) Array.get(ARRAY_PERSON, 1)
    assertEquals("Tom Hanks", person.getName());
}
if (ARRAY_INT.getClass().isArray() && ARRAY_INT.getClass().getComponentType() == int.class) {
    assertEquals(2, ((int) Array.get(ARRAY_INT, 1)));
}

5. Conclusion

In this article, we’ve learned two ways to check if a given object is an array.

We saw that if we use the instanceof  operator, we must cover the object array and all primitive array scenarios. On the other hand, the Class.isArray() approach is straightforward and it works for both object and all primitive arrays.

As usual, all code snippets presented in the article are available over on GitHub.

Course – LS – All

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

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.