1. 准备一个演示类
package my;
public class Data {
private static int data;
private String name;
private Data(){
}
private Data(int data,String name){
this.data = data;
this.name = name;
}
private void showName(){
System.out.println("Name is:"+name);
}
private static void showData(){
System.out.println("Data is:"+getData());
}
private static int getData(){
return data;
}
private void setData(int data){
this.data = data;
}
private void setString(String name){
this.name = name;
}
}
2.具体访问步骤
package my;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Start {
public static void main(String[] args) {
try {
Class dataType = Class.forName("my.Data");
// 访问私用的构造方法来创建对象实例
Constructor constructor = dataType
.getDeclaredConstructor(new Class[] { int.class,
String.class });
constructor.setAccessible(true);//访问私有成员方法,这句很关键
Data data = (Data) constructor.newInstance(new Object[] {
new Integer(50), new String("hello") });
// 开始访问私有的静态方法showData来打印对象信息
Method showDataMethod = dataType.getDeclaredMethod("showData",
new Class[] {});
showDataMethod.setAccessible(true);
showDataMethod.invoke(null, new Object[] {});//output:Data is:50
//开始访问私有方法showName来打印对象信息
Method showNameMethod = dataType.getDeclaredMethod("showName",
new Class[] {});
showNameMethod.setAccessible(true);
showNameMethod.invoke(data, new Object[] {});//output:Name is:hello
// 开始访问的setData方法来更改对象信息
Method setDataMethod = dataType.getDeclaredMethod("setData",
new Class[] { int.class });
setDataMethod.setAccessible(true);
setDataMethod.invoke(data, new Object[]{new Integer(100)});//设置data域 为100
//开始访问静态私有的成员变量
Field dataField = dataType.getDeclaredField("data");
dataField.setAccessible(true);
System.out.println(dataField.getInt(data));//output:100
dataField.setInt(null, 200);//再次修改私有成员data的值
System.out.println(dataField.getInt(data));//output:200
//开始访问私有成员变量
Field nameField = dataType.getDeclaredField("name");
nameField.setAccessible(true);
nameField.set(data,new String("Fuck!"));//修改私有变量name的值
showNameMethod.invoke(data, new Object[] {});//Name is:Fuck!
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
}
本文转自:http://blog.csdn.net/futuresherlock/article/details/6029091