square / javapoet

A Java API for generating .java source files.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Feature to insert new methods and fields after call JavaFile build.

maykon-oliveira opened this issue · comments

Hi, I'm so gland to find this lib, congrants to all colaborators.

So, I have a specific case to share, maybe this will become a new feature in the lib. I'm needing to add more components in the class on-demand, new methods, fields and etc. But after calling the build method of the JavaFile class to assemble the class, I can't after that, add new components. For example.

MethodSpec main =
        MethodSpec.methodBuilder("test")
            .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
            .returns(void.class)
            .addParameter(String[].class, "args")
            .addStatement("$T.out.println($S)", System.class, "Hello, JavaPoet!")
            .build();

    TypeSpec helloWorld =
        TypeSpec.classBuilder("ClassForSuiteOfTests")
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addMethod(main)
            .build();

    JavaFile javaFile = JavaFile.builder("br.com.tinuj.tinujlibrary", helloWorld).build();

    MethodSpec today =
        MethodSpec.methodBuilder("today")
            .returns(Date.class)
            .addStatement("return new $T()", Date.class)
            .build();

    //    Here throws java.lang.UnsupportedOperationException
    javaFile.typeSpec.methodSpecs.add(today);

    javaFile.writeTo(System.out);

It happens because here creates a immutableList, and I cannot insert new MethodSpec, or anything else.

My point is, what's the impact of allow add new components to an instance of JavaFile after build?

If it's ok to allow add new components to JavaFile, how about a new method to JavaFile that loads a java file source code and creates a JavaFile with Method Spec, TypeSpec, FieldSpec...?

If we were to make JavaFile mutable there would be no need for the builder. You can call toBuilder() to get back a mutable instance, or simply share the original builder instance and call build() at the end.