Public class reflecttest {private volatile string name = "before"; Public void setname (string name) {This. name = Name;} public static void main (string [] ARGs) {reflecttest test = new reflecttest (); try {system. out. println (getvalue (test, "name"); test. setname ("after"); system. out. println (getvalue (test, "name");} catch (illegalaccessexception e) {e. printstacktrace ();} catch (nosuchfieldexception e) {e. P Rintstacktrace () ;}} public static object getvalue (object instance, string fieldname) throws illegalaccessexception, nosuchfieldexception {field = getfield (instance. getclass (), fieldname); // If the parameter value is true, the access control check field is disabled. setaccessible (true); Return field. get (instance);} public static field getfield (class thisclass, string fieldname) throws nosuchfieldexception {If (fieldname = NULL) {Throw new nosuchfi Eldexception ("error field! ");} Field = thisclass. getdeclaredfield (fieldname); Return field ;}}
Print results
beforeafter