使用反射调用 Java 的私有方法,java私有,TheVictim.ja
分享于 点击 29193 次 点评:229
使用反射调用 Java 的私有方法,java私有,TheVictim.ja
TheVictim.java
package cn.outofmemory.demo;public class TheVictim { private void hackTest() { System.out.println("hackTest called"); } private static void hackTestStatic() { System.out.println("hackTestStatic called"); }}
HackTest.java
package cn.outofmemory.demo;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.lang.reflect.Modifier;public class HackTest { public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { Class c = TheVictim.class; Method[] ms = c.getDeclaredMethods(); for (Method each : ms) { String methodName = each.getName(); each.setAccessible(true); // this is the key if (Modifier.isPrivate(each.getModifiers())) { if (Modifier.isStatic(each.getModifiers())) { // static doesnt require the instance to call it. each.invoke(TheVictim.class, new Object[] {}); } else { each.invoke(new TheVictim(), new Object[] {}); } } } }}
用户点评