Saturday 16 August 2014

Getting and Setting Field Values

Setting values to a fieldat run time is two step process.

Step 1: Get the declared field by using getDeclaredField(String) or getField(String) method.

Step 2: After getting the field from step1, use the setter methods of Field class to set field.

class Employee {
    String address;
    String firstName, lastName;
    int id, age;
    String phoneNum;
}

import java.lang.reflect.Field;

public class GetFields {
    
   public static void display(Employee emp){
       System.out.println("---------------------------");
       System.out.println("firstName : " + emp.firstName);
       System.out.println("lastName : " + emp.lastName);
       System.out.println("id : " + emp.id);
       System.out.println("age : " + emp.age);
       System.out.println("phoneNum : " + emp.phoneNum);
       System.out.println("address : " + emp.address);
   }
   public static void main(String args[]) throws Exception{
       Employee emp = new Employee();
       Class myClass = emp.getClass();
       
       System.out.println("Setting firstName");
       Field myField = myClass.getDeclaredField("firstName");
       myField.set(emp, "Krishna");       
       display(emp);
       
       System.out.println("Setting id");
       myField = myClass.getDeclaredField("id");
       myField.setInt(emp, 1);
       display(emp);
       
       System.out.println("Setting age");
       myField = myClass.getDeclaredField("age");
       myField.setInt(emp, 26);
       display(emp);
   } 
}

Output
Setting firstName
---------------------------
firstName : Krishna
lastName : null
id : 0
age : 0
phoneNum : null
address : null
Setting id
---------------------------
firstName : Krishna
lastName : null
id : 1
age : 0
phoneNum : null
address : null
Setting age
---------------------------
firstName : Krishna
lastName : null
id : 1
age : 26
phoneNum : null
address : null



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment