Program to demonstrate working of Field class in Java Reflection API for getting field, setting and getting its value
Output of the program :
package com.hubberspot.example; import java.lang.reflect.Field; class Customer { public String firstname; public String lastname; public String email; public static int counter; } public class FieldDemo { public static void main(String[] args) { // Create a test object. We can create // and apply reflection on any class // we want without knowing which fields // it has. We are taking Customer here. Customer customer = new Customer(); // Getting Class associated with Customer Class demo = customer.getClass(); try { // Using Field class we can get field of any // class we want. Here we are getting field // firstname by calling getField method of the // Class associated with Customer Field field = demo.getField("firstname"); // After getting the field we are assigning it // with a value by using set method of Field // First parameter is the Object of Customer and // second parameter is the value we want to set field.set(customer, "Jonty"); // After assignment we are getting the value back // by using get method of Field and passing the // Object of Customer for which we want the value Object result = field.get(customer); // printing it to console System.out.println("Customer First Name is : " + result); // similarly doing for lastname and email field = demo.getField("lastname"); field.set(customer, "Magicman"); result = field.get(customer); System.out.println("Customer Last Name is : " + result); field = demo.getField("email"); field.set(customer, "Jonty@Magic.com"); result = field.get(customer); System.out.println("Customer Email is : " + result); field = demo.getField("counter"); // while working with static we are not passing // Object as Customer instance but we are // passing it a null because its static field field.set(null, 1); result = field.get(null); System.out.println("Customer Counter is : " + result); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } }
Output of the program :