Mega Code Archive

 
Categories / Java / Reflection
 

Get fields of a class object

import java.lang.reflect.Field; import java.util.Date; public class Main {   public static void main(String[] args) throws Exception {     GetFields object = new GetFields();     Class clazz = object.getClass();     // Get all object fields including public, protected, package and private     // access fields.     Field[] fields = clazz.getDeclaredFields();     System.out.println("Number of fields = " + fields.length);     for (Field field : fields) {       System.out.println("Field name = " + field.getName());       System.out.println("Field type = " + field.getType().getName());     }   } } class GetFields {   public Long id;   protected String name;   private Date birthDate;   Double weight; }