1

Is it possible to generate static initializer using javapoet? See an example of what I'm trying to generate below:

class Foo {
    static int one = 1;
    static int two = 2;
    static int sum;

    static {
        sum = one + two;
    }
}

I tried adding static initializer as a constructor with static modifier:

TypeSpec.classBuilder("Foo")
    .addField(FieldSpec.builder(int.class, "one", Modifier.STATIC).initializer("1").build())
    .addField(FieldSpec.builder(int.class, "two", Modifier.STATIC).initializer("2").build())
    .addField(int.class, "sum", Modifier.STATIC)
    .addMethod(MethodSpec.constructorBuilder()
        .addModifier(Modifier.STATIC)
        .addCode("sum = one + two;")
        .build())
    .build();

But this produces static Foo() { ... } instead of static {...}, which is incorrect syntax.

Is there a way to do it?

Denis Itskovich
  • 3,798
  • 3
  • 26
  • 48
  • @t0mppa, may be vice versa - that question is duplicate of mine (see the dates) – Denis Itskovich Dec 04 '18 at 06:24
  • Well, the other one has an answer that is up-to-date. This one has an answer that gives the wrong idea, since it was fixed a while after. I don't mind which way things go, but should be left with one main question that has an up-to-date answer. – t0mppa Dec 05 '18 at 08:57

1 Answers1

2

This cannot be done with version 1.0, the latest at time of writing.

However, there is a pull request to address this (https://github.com/square/javapoet/pull/257) which will hopefully be merged before the next release (most likely version 1.1).

Jake Wharton
  • 72,540
  • 21
  • 218
  • 227