public class test3 { /* * public void setProperity(object obj,String name, object value) * 此方法可将obj对象中的名为properityName的属性值 改为 value */ public static void main(String[] args) throws Exception { Student s = new Student("张三",23); System.out.println(s); Tool t = new Tool(); t.setProperity(s, "name", "李四"); 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); } }