Java Reflection field get field type

Introduction

A field may be

  • any of the eight primitive types (boolean, char, byte, short, int, long, float, and double)
  • a reference type (a direct or indirect subclass of java.lang.Object).

The class Field has two methods to know its type:

public Class<?> getType()  
public Type getGenericType()  

The following program shows all field names and their types of given class:

import java.lang.reflect.Field;

public class Main {
   public static void main(String args[]) throws Exception {
      Class c = Class.forName("java.lang.String");
      Field[] fields = c.getDeclaredFields();
      for (Field f : fields)
         System.out.println(f.getType() + " " + f.getName());
   }/*from   ww w. j  ava2  s  .c  o  m*/
}



PreviousNext

Related