如何使用CodeModel在方法内部“生成源代码”创建和初始化hashMap

时间:2018-07-05 12:27:40

标签: java sun-codemodel jcodemodel

要生成的源代码

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

1 个答案:

答案 0 :(得分: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>();
    }

}