反射访问私有属性、方法
包含私有属性、方法的类
public class privateObject {
private String privateStr = "this is a privateSting";
public void setPrivateStr(String str) {
this.privateStr = str;
}
private void printPrivateStr() {
System.out.println(this.privateStr);
}
private void printParmas(int param1, int param2) {
System.out.println(param1);
System.out.println(param2);
}
}
测试类
package example;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class TestMain {
public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
// 访问私有属性
privateObject privateObject = new privateObject();
Field privateStringField = privateObject.getClass().getDeclaredField("privateStr");
privateStringField.setAccessible(true);
System.out.println((String) privateStringField.get(privateObject));
// 访问私有方法
Method privateObjectMethod = privateObject.getClass().getDeclaredMethod("printPrivateStr", null);
privateObjectMethod.setAccessible(true);
privateObjectMethod.invoke(privateObject, null);
// 访问带参数的私有方法
Class[] cArg = new Class[2];
cArg[0] = int.class;
cArg[1] = int.class;
Method privateObjectMethod2 = privateObject.getClass().getDeclaredMethod("printParmas", cArg);
privateObjectMethod2.setAccessible(true);
privateObjectMethod2.invoke(privateObject, 1, 2);
}
}
注意:
privateObjectMethod2.setAccessible(true);用于设置语言检查访问(public/private/protect/default),true为关闭,false为打开。