欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

使用反射调用 Java 的私有方法,java私有,TheVictim.ja

来源: javaer 分享于  点击 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[] {});    }   }  } }}
相关栏目:

用户点评