我想通过使用cglib来挂钩context.startActivity,但得到了异常

时间:2017-04-06 01:51:26

标签: java android cglib

private void cghookMInstrumentation() throws Exception {

    //get mInstrumentation
    Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
    Method currentActivityThread = activityThreadClass.getDeclaredMethod("currentActivityThread");
    currentActivityThread.setAccessible(true);
    Object sCurrentActivityThread = currentActivityThread.invoke(null);//ActivityThread instance

    Method getInstrumentation = activityThreadClass.getDeclaredMethod("getInstrumentation");
    getInstrumentation.setAccessible(true);
    Instrumentation instrumentation = (Instrumentation) getInstrumentation.invoke(sCurrentActivityThread);//Instrumentation

    Field mInstrumentationField = activityThreadClass.getDeclaredField("mInstrumentation");
    mInstrumentationField.setAccessible(true);

    Enhancer enHancer = new Enhancer();
    CglibProxy cglibProxy = new CglibProxy();
    enHancer.setSuperclass(instrumentation.getClass());
    enHancer.setCallback(cglibProxy);

    Instrumentation mInstrumentation = (Instrumentation) enHancer.create();

    //replace Instrumentation
    mInstrumentationField.set(instrumentation, mInstrumentation);
}

例外:

Caused by: java.lang.UnsupportedOperationException: can't load this type of class file
 at java.lang.ClassLoader.defineClass(ClassLoader.java:300)
 at java.lang.reflect.Method.invoke(Native Method) 
 at net.sf.cglib.core.ReflectUtils.defineClass(ReflectUtils.java:384) 
 at net.sf.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:219) 
 at net.sf.cglib.core.KeyFactory$Generator.create(KeyFactory.java:145) 
 at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:117) 
 at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:108) 
 at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:104) 
 at net.sf.cglib.proxy.Enhancer.<clinit>(Enhancer.java:69) 
 at cn.chx.hooklib.CgLibHookClickListener.cghookMInstrumentation(CgLibHookClickListener.java:52) 
 at cn.chx.hooklib.CgLibHookClickListener.onClick(CgLibHookClickListener.java:28) 
 at android.view.View.performClick(View.java:5198) 
 at android.view.View$PerformClick.run(View.java:21147) 
 at android.os.Handler.handleCallback(Handler.java:739) 
 at android.os.Handler.dispatchMessage(Handler.java:95) 
 at android.os.Looper.loop(Looper.java:148) 
 at android.app.ActivityThread.main(ActivityThread.java:5417) 
 at java.lang.reflect.Method.invoke(Native Method) 
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

我想挂钩context.startActivity

ActivityThread -> currentActivityThread() -> mInstrumentation

我写了一个扩展Instrumentation的类并设置到mInstrumentationField,它工作正常,但我使用cglib我得到了这个异常;

我将不胜感激任何帮助。

1 个答案:

答案 0 :(得分:0)

Cglib无法在Android上运行。你想要做的是不可能的。您可以尝试Byte Buddy作为替代方案,其中包括Android的类加载策略,可以在Android上创建代理。