反射 - 通过反射机制访问私有成员变量
package com.xxxx; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * 通过反射修改私有成员变量的值 * * @author Dw * */ public class AccessPrivateMemVarWithReflect { public static void main(String[] args) throws Exception { Class<?> classType = Class.forName("com.xxxx.TestAccessPrivateMemVar"); Object test = classType.newInstance(); Field field = classType.getDeclaredField("name"); // 突破private权限 field.setAccessible(true); // 设置新值 field.set(test, "ZhangSan"); // 获取getName方法 Method getName = classType.getMethod("getName", new Class[] {}); // call System.out.println(getName.invoke(test, new Object[] {})); // ZhangSan field.set(test, "LiSi"); System.out.println(getName.invoke(test, new Object[] {})); // LiSi } } class TestAccessPrivateMemVar { private String name; public TestAccessPrivateMemVar() { // TODO Auto-generated constructor stub } public String getName() { return this.name; } }