问题
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?
回答1:
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).
来源:https://stackoverflow.com/questions/29828721/generating-static-class-initializer-using-javapoet