ByteBuddy:如何进行方法委派/转发到volatile字段

时间:2016-10-19 07:09:54

标签: java byte-buddy

我有(伪代码)这样​​的东西:

final Class<OUT> newClass = (Class<OUT>) new ByteBuddy()
.subclass(Object.class)
.name(newName)
.implement(SomeInterface.class, SomeOtherInterface.class)
.method(ElementMatchers.isMethod())                            
.intercept(
    ExceptionMethod.throwing(UnsupportedOperationException.class,
                            "calling this method is not supported"))
// in fact I am matching for more than a single method here
.method(ElementMatchers.named("getUuid"))
.intercept(
    MethodDelegation.toInstanceField(SomeOtherInterface.class, "delegate"))
.make()
.load(aBusinessEntityClass.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();

我当前的问题是:我需要委托字段为 volatile 。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:2)

使用Byte Buddy 1.5.0退出toInstanceField API,转而使用新的检测API,您可以明确定义该字段:

new ByteBuddy()
  .defineField("delegate", SomeOtherInterface.class, VOLATILE)
  .method(ElementMatchers.named("getUuid"))
  .intercept(MethodDelegation.toField("delegate"));

这允许执行其他操作,例如添加注释等。

现在,所有Implementation都实施了此方法。新版本于今天发布。

答案 1 :(得分:1)

好的,找到了适用于我的解决方案,万一有人感兴趣:

final Class<OUT> newClass = (Class<OUT>) new ByteBuddy()
.subclass(Object.class)
.name(newName)
.implement(SomeInterface.class, SomeOtherInterface.class)
.method(ElementMatchers.isMethod())                            
.intercept(
    ExceptionMethod.throwing(UnsupportedOperationException.class,
                        "calling this method is not supported"))
// in fact I am matching for more than a single method here
.method(ElementMatchers.named("getUuid"))
.intercept(
    MethodDelegation.toInstanceField(SomeOtherInterface.class, "delegate"))
// -- HERE THE FIELD IS MODIFIED AGAIN, IN THIS CASE AS  --
// -- PRIVATE & VOLATILE                                 --
.field(ElementMatchers.named("delegate"))                       
.transform(Transformer.ForField.withModifiers(FieldManifestation.VOLATILE, Visibility.PRIVATE))
.make()
.load(aBusinessEntityClass.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();

解决方案是通过使用 transform()和相应的 Transformer.ForField.withModifiers()调用 field()来修改字段。 EM>

希望能帮助每个人面对这个问题。

相关问题