2

要生成的源代码

class SomeClass{

    public void someMethod(){

         HashMap<String,String> map = new HashMap<String,String>();

       }

  }

能够创建为全局变量,但我需要在方法中创建它

            JClass keyType = codeModel.ref(Object.class);
            JClass valueType = codeModel.ref(Object.class);
            JClass mapClass = codeModel.ref(Map.class).narrow(keyType, valueType);
            JClass hashMapClass = codeModel.ref(HashMap.class).narrow(keyType, valueType);
            headers = definedClass.field(JMod.PRIVATE, mapClass, "headers").init(JExpr._new(hashMapClass));
4

1 回答 1

2

如果我正确理解您的问题,那么您正在寻找在方法中初始化变量。您可以通过在方法主体中声明和初始化变量来做到这一点:

    JDefinedClass derived = codeModel._class(JMod.PUBLIC, "SomeClass", ClassType.CLASS);
    JClass keyType = codeModel.ref(String.class);
    JClass valueType = codeModel.ref(String.class);
    JClass mapClass = codeModel.ref(Map.class).narrow(keyType, valueType);
    JClass hashMapClass = codeModel.ref(HashMap.class).narrow(keyType, valueType);

    JMethod method = derived.method(JMod.PUBLIC, codeModel.VOID, "createHeaders");

    JBlock body = method.body();

    JVar headers = body.decl(mapClass, "headers", JExpr._new(hashMapClass));

生成:

public class SomeClass {


    public void createHeaders() {
        Map<String, String> headers = new HashMap<String, String>();
    }

}
于 2018-07-05T16:04:39.317 回答