如何利用反射去访问一个私有的方法
package com.java.lesson.reflect;
public class PrivateTest {
private String name = "zhang";
public String getName() { return name; }
private String sayTo(String name) { return " hello ----- " + name; }
}
===================
package com.java.lesson.reflect;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class TestPrivate {
public static void main(String[] args) throws Exception {
PrivateTest p = new PrivateTest();
Class<?> classType = p.getClass();
Method method = classType.getDeclaredMethod("sayTo", new Class[] { String.class });
method.setAccessible(true);
Object object = method.invoke(p, new Object[] { "sxz" });
System.out.println(object);
// =========================================================
Field field = classType.getDeclaredField("name");
field.setAccessible(true);
field.set(p,"lisi");
System.out.println(p.getName());
}
}
posted on 2012-02-20 23:00 shixinzhu 阅读(1349) 评论(0) 编辑 收藏 举报