反射访问私有属性、方法

包含私有属性、方法的类

  1. public class privateObject {
  2. private String privateStr = "this is a privateSting";
  3. public void setPrivateStr(String str) {
  4. this.privateStr = str;
  5. }
  6. private void printPrivateStr() {
  7. System.out.println(this.privateStr);
  8. }
  9. private void printParmas(int param1, int param2) {
  10. System.out.println(param1);
  11. System.out.println(param2);
  12. }
  13. }

测试类

  1. package example;
  2. import java.lang.reflect.Field;
  3. import java.lang.reflect.InvocationTargetException;
  4. import java.lang.reflect.Method;
  5. public class TestMain {
  6. public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
  7. // 访问私有属性
  8. privateObject privateObject = new privateObject();
  9. Field privateStringField = privateObject.getClass().getDeclaredField("privateStr");
  10. privateStringField.setAccessible(true);
  11. System.out.println((String) privateStringField.get(privateObject));
  12. // 访问私有方法
  13. Method privateObjectMethod = privateObject.getClass().getDeclaredMethod("printPrivateStr", null);
  14. privateObjectMethod.setAccessible(true);
  15. privateObjectMethod.invoke(privateObject, null);
  16. // 访问带参数的私有方法
  17. Class[] cArg = new Class[2];
  18. cArg[0] = int.class;
  19. cArg[1] = int.class;
  20. Method privateObjectMethod2 = privateObject.getClass().getDeclaredMethod("printParmas", cArg);
  21. privateObjectMethod2.setAccessible(true);
  22. privateObjectMethod2.invoke(privateObject, 1, 2);
  23. }
  24. }

注意:

privateObjectMethod2.setAccessible(true);用于设置语言检查访问(public/private/protect/default),true为关闭,false为打开。