主函数:
import java.lang.reflect.Field;public class reflec { public static void main(String[] args) throws NoSuchMethodException, ClassNotFoundException, IllegalAccessException { TestClassEx t = new TestClassEx(); for (Field f : t.getClass().getDeclaredFields()) { if(f.getName().equals("leijun")) { f.setAccessible(true); f.set(t, "indian MI fans"); System.out.println(f.getName()+":"+f.get(t)); } } }}
实体类:
class TestClassEx extends TestClass{ public String leijun = "are you ok?";}
运行结果:
leijun:indian MI fans
Process finished with exit code 0