Generating static class initializer using javapoet [duplicate]

蓝咒 提交于 2019-12-11 13:07:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!