javaseeker
javaseeker

Reputation: 63

Create a class and its methods from scratch using byte-buddy

Is it possible to create a whole new class and methods in it with bytebuddy?

All examples that I see uses an existing class or intercept to an existing method to modify them.

Are there any examples which constructs a class and add some methods dynamically through bytebuddy and returns the instance of the class ?

Upvotes: 0

Views: 1695

Answers (1)

k5_
k5_

Reputation: 5568

All Java classes need to extend another class, so you need to extends at least Object.class. Using interfaces or replacing methods from existing classes, makes them usable without heavy use of reflection, so that is what many people to. But that is not necessary.

Subclass Object.class add your methods/fields and delegate to the actual methods you have written in java. The "Hello World" example does exactly that.

Class<?> dynamicType = new ByteBuddy()
  .subclass(Object.class)
  .method(ElementMatchers.named("toString"))
  .intercept(FixedValue.value("Hello World!"))
  .make()
  .load(getClass().getClassLoader())
  .getLoaded();

assertThat(dynamicType.newInstance().toString(), is("Hello World!"));

Byte Buddy can create dynamic methods bodies, but in that case you basically write java assembler. If you want help with that, you might want to ask a more specific question about what you want to create.

If you can fit your needs into the annotation/convention/intercept/delegate approach of bytebuddy, i would strongly suggest you try to use it. Your code will be debugable (you can set breakpoints in the delegates) and is generated by somebody who knows how to write correct java assembler (javac and byte-buddy for the glue).

Upvotes: 1

Related Questions