Determine If a field is an array in Java

Description

The following code shows how to determine If a field is an array.

Example


/*from   w w  w .j  a  va2 s  .c o  m*/
import static java.lang.System.out;

import java.lang.reflect.Field;

public class Main {
  public static void main(String... args) {
    boolean found = false;
    try {
      Class<?> cls = Class.forName(args[0]);
      Field[] flds = cls.getDeclaredFields();
      for (Field f : flds) {
        Class<?> c = f.getType();
        if (c.isArray()) {
          found = true;
          out.format("%s%n" + "           Field: %s%n"
              + "            Type: %s%n" + "  Component Type: %s%n", f, f
              .getName(), c, c.getComponentType());
        }
      }
      if (!found) {
        out.format("No array fields%n");
      }

      // production code should handle this exception more gracefully
    } catch (ClassNotFoundException x) {
      x.printStackTrace();
    }
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Reflection »




Annotation
Array
Class
Constructor
Field
Generics
Interface
Method
Modifier
Package
Proxy