【问题标题】:Byte Buddy - How to delegate a private method?Byte Buddy - 如何委托私有方法?
【发布时间】:2019-07-04 19:05:43
【问题描述】:

我有以下单元测试:

@Test
public void TestPrivateMethodDelegation() throws InstantiationException, IllegalAccessException, IllegalArgumentException, 
    InvocationTargetException, NoSuchMethodException, SecurityException
{
    Foo foo = new ByteBuddy()
        .subclass(Foo.class)
        .method(named("getHello")
            .and(isDeclaredBy(Foo.class)
            .and(returns(String.class))))
        .intercept(MethodDelegation.to(new Bar()))
        .make()
        .load(Foo.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent())
        .getLoaded()
        .getDeclaredConstructor().newInstance();

    Method privateMethod = Foo.class.getDeclaredMethod("getHello");
    privateMethod.setAccessible(true);

    assertEquals(privateMethod.invoke(foo), new Bar().getHello());
}

这是它使用的类:

@NoArgsConstructor
public class Foo 
{
    @SuppressWarnings("unused")
    private String getHello()
    {
        return "Hello Byte Buddy!";
    }
}

@NoArgsConstructor
public class Bar 
{
    public String getHello()
    {
        return "Hello Hacked Byte Buddy!";
    }
}

当我在 Foo 类中公开 getHello() 方法时,此测试通过。当我将其保留为私有时,测试失败,因为我只能假设私有方法未正确委派。

甚至可以将私有方法委托给另一个类吗?

谢谢!

【问题讨论】:

    标签: java methods private delegation byte-buddy


    【解决方案1】:

    不,不是。 Byte Buddy 生成字节码就像 javac 会做的那样,这个字节码必须是有效的才能运行。您不能从另一个类调用私有方法,因此,Byte Buddy 正在引发异常。

    【讨论】:

    • 谢谢拉斐尔。我必须说,你创造了一个伟大的产品,你清楚地支持它,因为我几乎在我看到的每一个 ByteBuddy 帖子上都看到了你的名字。来自加拿大的干杯!
    • 谢谢,很高兴你喜欢这个图书馆!
    猜你喜欢
    • 1970-01-01
    • 2021-02-12
    • 2013-03-16
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-20
    • 1970-01-01
    相关资源
    最近更新 更多