Use reflection to check array type and length in Java

Description

The following code shows how to use reflection to check array type and length.

Example


//from   ww w . j  a va2  s.  c om
import java.lang.reflect.Array;

public class Main {
  public static void main(String args[]) {
    String data[] = new String[3];
    data[0] = "Java";
    printType(data);
  }

  private static void printType(Object object) {
    Class type = object.getClass();
    if (type.isArray()) {
      Class dataType = type.getComponentType();
      System.out.println("Array of: " + dataType);
      System.out.println(" Length: " + Array.getLength(object));
    }
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Reflection »




Annotation
Array
Class
Constructor
Field
Generics
Interface
Method
Modifier
Package
Proxy