为了账号安全,请及时绑定邮箱和手机立即绑定

字节好友 - 如何委托私有方法?

字节好友 - 如何委托私有方法?

蝴蝶刀刀 2023-03-09 10:22:20
我有以下单元测试:@Testpublic 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());}这是它使用的类:@NoArgsConstructorpublic class Foo {    @SuppressWarnings("unused")    private String getHello()    {        return "Hello Byte Buddy!";    }}@NoArgsConstructorpublic class Bar {    public String getHello()    {        return "Hello Hacked Byte Buddy!";    }}当我在 Foo 类中公开 getHello() 方法时,此测试通过。当我将其保留为私有时,测试失败,因为我只能假设私有方法未正确委派。甚至可以将私有方法委托给另一个类吗?
查看完整描述

1 回答

?
呼唤远方

TA贡献1856条经验 获得超11个赞

不它不是。Byte Buddy 像javac一样生成字节码,并且该字节码必须有效才能运行。您不能从另一个类调用私有方法,因此,Byte Buddy 会抛出异常。



查看完整回答
反对 回复 2023-03-09
  • 1 回答
  • 0 关注
  • 78 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信