import java.lang.reflect.Field; public class TestReflection { public static void main(String args[]) throws Exception { Student someStudent = new Student(); // get information for field firstName - note it is private Field fs = someStudent.getClass().getDeclaredField("firstName"); // make the field accessible fs.setAccessible(true); // display the value of the field; note someStudent.firstName illegal System.out.println("Value of " + fs.getName() + ": " + fs.get(someStudent)); if (!fs.get(someStudent).equals("Sampath")) throw new AssertionError("Not Sampath"); // can also modify the value fs.set(someStudent, "Trisha"); System.out.println("Value of " + fs.getName() + " after changing: " + fs.get(someStudent)); if (!fs.get(someStudent).equals("Trisha")) throw new AssertionError("Could not change to Trisha"); } } class Student { private String firstName = "Sampath"; }