【问题标题】:Method Delegation to Self方法委托给自己
【发布时间】:2020-06-05 18:11:41
【问题描述】:

我想使用 Byte-Buddy 生成一个类,该类将接口方法委托给从超类继承的方法。

下面的两个代码sn-ps就是这样做的:

Class<? extends Object> clazz = new ByteBuddy()
    .subclass(serviceSuperClass)
    .name(className) 
    .implement(serviceInterface)
    .defineField(generalInterceptor, GrandFatherProxy.class, Visibility.PUBLIC)
    .method(isDeclaredBy(serviceInterface))
    .intercept(MethodDelegation.toField(generalInterceptor))
    .make ()
    .load(classLoader)
    .getLoaded();

在这种情况下,GrandFatherProxy.class 是给定 serviceSuperClass 的超类,因此属于 clazz。

一旦我使用 Reflection 生成了 clazz 的实例,我就可以使用该实例设置字段 generalInterceptor:

Field field = instance.getClass().getDeclaredField(generalInterceptor);
field.setAccessible(true);
field.set(instance, instance);  // set field on instance to contain instance!

这可行:Clazz 现在委托给自己:所有接口方法都被 @RuntimeType intercept() 方法拦截,clazz 继承自 GrandFatherProxy.class。

但是,如果我可以明确地指示 Byte-Buddy 进行自我委托,那就更加优雅了。

例如类似:

Class<? extends Object> clazz = new ByteBuddy()
    .subclass(serviceSuperClass)
    .name(className) 
    .implement(serviceInterface)
    .method(isDeclaredBy(serviceInterface))
    .intercept(MethodDelegation.toSelf())
    .make ()
    .load(classLoader)
    .getLoaded();

toSelf() 是我的伪代码,用于指示 Byte-Buddy 生成的类应该委托给它自己。

我是否错过了执行此操作的方法?还是需要对 Byte-Buddy 进行更改?

【问题讨论】:

    标签: java byte-buddy


    【解决方案1】:

    您可以通过定义一个返回 this 的私有方法来欺骗自己,然后在此方法上使用 MethodDelegation.toMethodReturnOf。要添加此功能,需要对库进行更改。

    【讨论】:

    • 虽然这种巧妙的技巧可能会奏效,但它可能不会提高 Byte-Buddy 配置的可读性。我目前的方法(定义一个字段+拦截该字段的方法+通过反射使用动态实例设置字段仍然是合理可读的)。我猜想一个显式的 toSelf() (或类似的构造)将需要一个库更改(但一个很好的)。我会在你的 Github 上打开一个更改请求。
    猜你喜欢
    • 2012-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-17
    • 2014-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多