Search code examples
byte-buddy

Can I create a ByteBuddy instrumented type with a private static final MethodHandle field in it?


I have asked a similar question in the past but could not make it work (it was not clear if it was possible).

Now I find myself in a situation where I need to make a private static final field whose type (in my case) is MethodHandle.

In Java, of course, I could simply do:

private static final MethodHandle mh = goGetMethodHandle();

…where goGetMethodHandle() is a static function that returns the MethodHandle I need.

Or, equivalently, I could do:

private static final MethodHandle mh;
static {
  mh = goGetMethodHandle();
}

I am not sure what the ByteBuddy recipe should be here.


Solution

  • Your solution can be accomplished more easily using the DSL:

    builder
      .defineField("gorp", MethodHandle.class, 
         Visibility.PRIVATE, Ownership.STATIC, SyntheticState.SYNTHETIC, FieldManifestation.FINAL)
      .invokeable(isTypeInitializer())
      .intercept(MethodCall.invoke(Some.class.getMethod("goGetMethodHandle")
        .setsField(named("gorp")))