7

How can I use Byte Buddy to add an annotation with a given value?

I'm playing around with generating test classes for JUnit and I'd like to annotate a generated class by @RunWith(SomeRunner.class).

Rafael Winterhalter
  • 42,759
  • 13
  • 108
  • 192
Kimble
  • 7,295
  • 4
  • 54
  • 77

1 Answers1

10

You can annotate a class within the fluent API:

new ByteBuddy()
  .subclass(Object.class)
  .annotateType(AnnotationDescription.Builder.ofType(RunWith.class)
                                             .define("value", SomeRunner.class)
                                             .build())
  .make();

Alternatively to the AnnotationDescription.Builder you can also hand over a loaded annotation, the builder automatically converts it to the internal description format.

Mark Chesney
  • 1,082
  • 12
  • 20
Rafael Winterhalter
  • 42,759
  • 13
  • 108
  • 192
  • The loaded annotation can be converted by `annotationDescription.ForLoadedAnnotation.of(field.getAnnotation(RunWith.class))` – alea Jul 11 '23 at 05:39