如何 "generate source code" 使用 CodeModel 在方法内创建和初始化 hashMap

How to "generate source code" create and initialise of a hashMap inside a method using CodeModel

要生成的源代码

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));

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

    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>();
    }

}