How do I get the component type of array?

The Class.getComponentType() method call returns the Class representing the component type of array. If this class does not represent an array class this method returns null reference instead.

package org.kodejava.lang.reflect;

public class ComponentTypeDemo {
    public static void main(String[] args) {
        String[] words = {"and", "the"};
        int[][] matrix = {{1, 1}, {2, 1}};
        Double number = 10.0;

        Class<?> clazz = words.getClass();
        Class<?> cls = matrix.getClass();
        Class<?> clz = number.getClass();

        // Gets the type of array component.
        Class<?> type = clazz.getComponentType();
        System.out.println("Words type: " +

        // Gets the type of array component.
        Class<?> matrixType = cls.getComponentType();
        System.out.println("Matrix type: " +

        // It will return null if the class doesn't represent
        // an array.
        Class<?> numberType = clz.getComponentType();
        if (numberType != null) {
            System.out.println("Number type: " +
        } else {
            System.out.println(number.getClass().getName() +
                    " class is not an array");

This program print the following output:

Words type: java.lang.String
Matrix type: int[]
java.lang.Double class is not an array

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.