square / javapoet

A Java API for generating .java source files.
Apache License 2.0
10.83k stars 1.38k forks source link

Update to support generate record from java 14 #981

Open zzBBc opened 1 year ago

zzBBc commented 1 year ago

Motivation:

Modifications:

Can you please review and merge the PR @JakeWharton

Duzhinsky commented 1 year ago

I think it is the most desirable feature for javapoet, but unfortunately, the tool maintenance consists only of small fixes. PR #840 does the same, but still not merged. The future of javapoet is discussed here. You could use the FabricMC/javapoet fork If you want to use records

lenis0012 commented 1 year ago

+1 on this.

In the mean time for those who dont want to use a fork, there is another workaround for inner records (not top-level).
I am simply doing a string replace after saving the fie:

return MethodSpec.methodBuilder("Record__%sEvent".formatted(toTypeName(name)))
    .addModifiers(Modifier.PUBLIC)
    // ....

This creates a public void Record__MyEvent(String a, int b, boolean c) {} Which I then replace:

try(
    OutputStreamWriter outputStream = new OutputStreamWriter(sourceFile.openOutputStream());
    StringWriter writer = new StringWriter()
) {
    JavaFile.builder(element.getQualifiedName().toString(), result)
        .indent("    ")
        .build()
        .writeTo(writer);
    outputStream.write(writer.toString().replace("void Record__", "record "));
}

Not the most elegant solution but it works. I am using inner records but you can do the same for top-level records using classes. Although it would be a bit more painful.

Jonpez2 commented 1 year ago

Is this likely to land at any point? Records are extremely nice, just like javapoet!

Randgalt commented 8 months ago

I'm planning on publishing this as a separate repo. See here: https://github.com/Randgalt/java-composer. Unless @JakeWharton/Square objects.

Randgalt commented 8 months ago

FYI - I've released v 1.0 of Java Composer with this change in it as well as support for sealed classes: https://github.com/Randgalt/java-composer