2

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));
Monis Majeed
  • 1,358
  • 14
  • 21

1 Answers1

2

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

}
John Ericksen
  • 10,995
  • 4
  • 45
  • 75
  • Thanks for the answer , can you please comment on the below question , i am in really need . https://stackoverflow.com/questions/55790450/how-to-initialise-a-2d-array-using-codemodel – Monis Majeed Apr 23 '19 at 05:18