Carsten Tolkmit Carsten Tolkmit - 1 month ago 14
Java Question

ByteBuddy: How to do method delegation / forwarding to a volatile field

I have (pseudo code) something like this:

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();


My current problem is: I need my delegate field to be volatile. How can I achieve that?

Answer

Okay, found a solution that works for me, in case anyone is interested:

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();

The solution was to modify the field afterwards with a call to field() with transform() and appropriate Transformer.ForField.withModifiers().

Hope to help everyone facing this issue.

Comments