How to get a Fields of a Class Object


Field (java.lang.reflect.Field) :
  • Implements Member Interface
  • Provides information about, and dynamic access to, a Single field (  also for static fields )
  • Provides access and modification ( set, get ) methods
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;


public class GetFieldsExample {
private int i = 10;
public String strname;
Long longField;
protected Date date;
ArrayList list;
  public static void main(String[] args) {
GetFieldsExample test = new GetFieldsExample();
Class objClass = test.getClass();
Field[] fields = objClass.getDeclaredFields();
// The getDeclaredFields returns all type of fields of the Object
for (Field field : fields) {
System.out.println("************************");
System.out.println("Field Name : " + field.getName());
System.out.println("Field Type : " + field.getType().getName());
}
// To get specific Field name
try {
Field field = objClass.getField("strname");
System.out.println("************************");
System.out.println("Field Name : " + field.getName());
System.out.println("Field Type : " + field.getType().getName());
} catch (NoSuchFieldException e) {
System.out.println("NoSuchField : "+e.getMessage());
}
}
}


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email