要生成的源代码
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));
答案 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>();
}
}