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

232 views Asked by At

Source Code to generate

class SomeClass{

    public void someMethod(){

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

       }

  }

Able to create as a global variable but i need to create it inside a method

            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

There are 1 answers

1
John Ericksen On BEST ANSWER

If I understand your question right, you're looking to initialize a variable in a method. You can do this by declaring and initializing the variable in a method body:

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

which generates:

public class SomeClass {


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

}