Get field type and generic type by field name in Java

Description

The following code shows how to get field type and generic type by field name.

Example


// w  ww  .jav a  2s.  c  om
import java.lang.reflect.Field;
import java.util.List;

class FieldSpy<T> {
  public boolean[][] b = { { false, false }, { true, true } };
  public String name = "Alice";
  public List<Integer> list;
  public T val;

}

public class Main {
  public static void main(String... args) {
    try {
      Class<?> c = Class.forName("FieldSpy");
      Field f = c.getField("name");
      System.out.format("Type: %s%n", f.getType());
      System.out.format("GenericType: %s%n", f.getGenericType());

      // production code should handle these exceptions more gracefully
    } catch (ClassNotFoundException x) {
      x.printStackTrace();
    } catch (NoSuchFieldException 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