Get all accessible public fields in Java

Description

The following code shows how to get all accessible public fields.

Example


/*from  w ww.ja  v  a  2s . c  o  m*/
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 accessible public fields.
    Field[] fields = clazz.getFields();
    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());
    }

    Field field = clazz.getField("id");
    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;

}

The code above generates the following result.





















Home »
  Java Tutorial »
    Reflection »




Annotation
Array
Class
Constructor
Field
Generics
Interface
Method
Modifier
Package
Proxy