是否可以在Android中用ByteBuddy替换类的方法?
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在某种程度上是可能的,还是有替代方案?
由于
答案 0 :(得分:1)
您的ModifiedDoSomething::saySomethign
方法不是static
。如果要委托实例方法,则需要运行MethodDelegation.to(new ModifiedSomething())
。