2017-01-12 126 views
0

是否有可能在Android中用ByteBuddy替換一個類的方法?在Android上可以使用ByteBuddy進行MethodDelegation攔截嗎?

public class DoSomething { 
    public void saySomething() { 
     Log.d("DoSomething", "Hello World"); 
    } 
} 

public class ModifiedDoSomething { 
    public void saySomething() { 
     Log.d("ModifiedDoSomething", "Hello Injected"); 
    } 
} 

new ByteBuddy() 
    .subclass(DoSomething.class) 
    .method(ElementMatchers.named("saySomething")) 
    .intercept(MethodDelegation.to(ModifiedDoSomething.class)) 
    .make() 
    .load(DoSomething.class.getClassLoader(), 
     new AndroidClassLoadingStrategy(f)) 
    .getLoaded() 
    .newInstance() 
    .saySomething(); 

當我嘗試此代碼時,它拋出:

java.lang.IllegalArgumentException: None of [] allows for delegation from public void DoSomething.saySomething() 

當我FixedValue攔截,它工作得很好,但我需要完全替代方法的實現或至少攔截開始,然後再調用原來的攔截。這在某種程度上可能與ByteBuddy一起使用還是有其他選擇?

感謝

回答

1

ModifiedDoSomething::saySomethign方法不static。如果您想委派實例方法,則需要運行MethodDelegation.to(new ModifiedSomething())

相關問題