code highlighting produced by actipro codehighlighter (freeware) http://www. codehighlighter.com/-->import java.lang.reflect.field;public class fieldtest { int i; public float f; protected boolean b; private string s; public fieldtest () { i=0; f=0.0f; b = true; s = ""; } public static void main (String[] args) { //class instantiation: fieldtest Fieldtest = new fieldtest (); //gets the domain of the class field[ ] declaredfields = fieldtest.class.getdeclaredfields (); for (int i=0;i<declaredfields.length;i++) { Field field = declaredFields[i]; system.out.println ("name is:" +field.getname ()); class fieldtype = field.gettype (); system.out.println ("Type:" +field.gettype ()); boolean isTurn = true; while (Isturn) { try{ isTurn = false; system.out.println ("The value before modification is:" + field.get (FieldTest)) ; if (Fieldtype.equals (int.class)) { system.out.println (" Use the Setint () method to modify the value of the member variable. "); &nBsp; field.setint (fieldtest, 124); } else if ( Fieldtype.equals (Float.class)) { system.out.println ("Using SetFloat () Method modifies the value of the member variable. "); field.setfloat (fieldtest, 9.9f); }else if ( Fieldtype.equals(Boolean.class)) { &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("Use the SetBoolean () method to modify the value of the member variable."); field.setboolean (Fieldtest, false); } else { &NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("Use the Set () method to modify the value of the member variable."); field.set (fieldtest, "Nwq"); } SYSTEM.OUT.PRINTLN ("Modified value:" +field.get (fieldtest)); }catch (exception e) { system.out.println ("An exception occurred while setting the member variable, Executes the setaccessible () method. "); //Modify Accessibility, if true, all members of the current domain can access field.setaccessible ( True); isTurn = true; } } system.out.println ("**************"); } }}
Simple use of the Java Field reflection mechanism