Terry K.
Terry K.

Reputation: 63

ByteBuddy how to create a class file?

I'm trying to create a class with annotation processor using ByteBuddy at build time.

I want to create a class and generate source file then generated source file could be invoked and used at runtime.

I want to know what I should do or if I am doing something wrong.

hope your help sincerely. 😂

This is a class That I want to create.


    public class EntitySource {
      static Stream entitySource() {
        return Stream.of(new Member(1L));
      }
    }

And here is my implementation.

    File sourceDirectory = new File("Something path of directory");
    sourceDirectory.mkdirs();
    File sourceFile = new File("Something path of directory" + "/EntitySource.java");
    sourceFile.createNewFile();

    new ByteBuddy()
      .subclass(Object.class)  
      .name(generatedClassName)
      .defineMethod("entitySource", Stream.class, Ownership.STATIC, Visibility.PACKAGE_PRIVATE)
      // .defaultValue(FixedValue.value(Stream.of(modelClass.getConstructor(Long.class).newInstance(1L))), Stream.class)
      .intercept(FixedValue.value(Stream.of(modelClass.getConstructor(Long.class).newInstance(1L))))
      .make()
      .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.INJECTION)
      .inject(sourceFile);

Contrary to my expectations, generated source is below.. (in intellij IDEA)

[enter image description here](https://i.sstatic.net/c1wDZ.png)

Upvotes: 1

Views: 457

Answers (1)

Rafael Winterhalter
Rafael Winterhalter

Reputation: 43972

Byte Buddy generates class, not source files.

For source file generation, have a look at Java Poet.

Upvotes: 2

Related Questions