Saturday 16 August 2014

Fields accessing using reflection

By using Java reflection you can get all the fields, set the fields at run time.

Getting all the fields
class Employee {
    private String address;
    String firstName, lastName;
    protected int id, age;
    public String phoneNum;
}

import java.lang.reflect.Field;

public class GetFields {
   public static void main(String args[]){
       Class myClass = Employee.class;
       
       Field[] fields = myClass.getDeclaredFields();
       
       System.out.println("Fields declared in this class are");
       for(Field field : fields)
           System.out.println(field.getName());
   } 
}

Output
Fields declared in this class are
address
firstName
lastName
id
age
phoneNum

There is another method 'getFields' which return only public fields.

import java.lang.reflect.Field;

public class GetFields {
   public static void main(String args[]){
       Class myClass = Employee.class;
       
       Field[] fields = myClass.getFields();
       
       System.out.println("Fields declared in this class are");
       for(Field field : fields)
           System.out.println(field.getType() +" " + field.getName());
   } 
}

Output
Fields declared in this class are
class java.lang.String phoneNum






Prevoius                                                 Next                                                 Home

No comments:

Post a Comment