简体   繁体   中英

Is MethodDelegation intercept with ByteBuddy possible on Android?

is it possible to replace a method of a class with ByteBuddy in Android?

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();

When I try this code, it throws:

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

When I intercept with FixedValue, it works just fine, however I would need to completely replace the implementation of the method or at least to intercept the beginning, call the original and then intercept in the end again. Is this somehow possible with ByteBuddy or are there alternatives?

Thanks

Your ModifiedDoSomething::saySomethign method is not static . If you want to delegate to an instance method, you need to run MethodDelegation.to(new ModifiedSomething()) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM