【发布时间】:2016-10-11 21:56:22
【问题描述】:
我正在尝试在 bytebuddy 中委派一个私有方法 - 但如何调用“覆盖”版本?如果我有
TypePool typepool = TypePool.Default.ofClassPath();
new ByteBuddy()
.rebase(typepool.describe("Foo").resolve(), ClassFileLocator.ForClassLoader.ofClassPath())
.method(named("getNum"))
.intercept(MethodDelegation.to(typepool.describe("FooInterceptor").resolve()))
.make()
.load(typepool.describe("Foo").resolve().getClass().getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
Foo foo1 = new Foo();
System.out.println("Foo says " + foo1.getMessage());
和
public class Foo
{
private int num = 0;
public String getMessage()
{
return "Message is Foo " + getNum();
}
private int getNum()
{
return num++;
}
}
和
import net.bytebuddy.implementation.bind.annotation.Super;
public class FooInterceptor
{
public static int getNum(@Super Foo foo)
{
// This won't work!
return foo.getNum() + 100;
}
}
就编译器而言,即使@Super Foo foo 在运行时会变成别的东西,我也不能在 Foo 上调用私有方法。我似乎也无法反映/调用getNum() - 无论@Super Foo 变成什么,它似乎都没有getNum() 方法(尽管它确实有getMessage() 方法)。
有人可以在这里指出我正确的方向吗?
更新:
@Rafael 的回答在技术上是对我提出的问题的一个很好的解决方案;不幸的是,我想我的例子很糟糕。过失。我真正希望的是一个解决方案,它可以让我在传递参数之前操纵getNum() 的参数。但事实证明,对于我的应用程序,我可能不这样做就可以过关,所以如果情况发生变化,那么也许我会发布那个确切的例子。
更新 2:
问题已完全回答!欢呼!
【问题讨论】:
标签: java reflection byte-buddy