Get array component type in Java

Description

The following code shows how to get array component type.

Example


/*from w w  w.ja  va  2s  .  c  om*/
import java.awt.Button;

public class Main{

  public static void main(String[] args) {
    int[] ints = new int[2];
    Button[] buttons = new Button[6];
    String[][] twoDim = new String[4][5];

    printComponentType(ints);
    printComponentType(buttons);
    printComponentType(twoDim);
  }

  static void printComponentType(Object array) {
    Class arrayClass = array.getClass();
    String arrayName = arrayClass.getName();
    Class componentClass = arrayClass.getComponentType();
    String componentName = componentClass.getName();
    System.out.println("Array: " + arrayName + ", Component: "
        + componentName);
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Reflection »




Annotation
Array
Class
Constructor
Field
Generics
Interface
Method
Modifier
Package
Proxy