Java Reflection - Java Field.getGenericType()








Syntax

Field.getGenericType() has the following syntax.

public Type getGenericType()

Example

In the following code shows how to use Field.getGenericType() method.

import java.lang.reflect.Field;
import java.util.List;
/*from  w  w w  .j av a  2  s  . c o  m*/
public class Main<T> {
  public boolean[][] b = { { false, false }, { true, true } };
  public String name = "Alice";
  public List<Integer> list;
  public T val;

  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.