public class Test3 { / * * public void setProperity (Object obj, String name, Object value) * This method may be called properityName attribute value of the object obj was changed value * / public static void main (String [] args) throws Exception { Student S = new new Student ( "Joe Smith", 23 is ); System.out.println (S); Tool T = new new Tool (); t.setProperity (S, "name", "John Doe" ); System.out.println (S); } }
import java.lang.reflect.Field; public class Tool { public void setProperity(Object obj,String name, Object value) throws Exception{ Class clazz = obj.getClass(); Field f = clazz.getDeclaredField(name); f.setAccessible(true); //取出权限 f.set(obj, value); } }