I want to declare and instantiate a HashMap in one go in JCodeModel.
I do:
jc.field(JMod.PRIVATE, HashMap.class, "initAttributes");
which declares it but doesn't instantiate it. How do I instantiate it?
Thanks
I want to declare and instantiate a HashMap in one go in JCodeModel.
I do:
jc.field(JMod.PRIVATE, HashMap.class, "initAttributes");
which declares it but doesn't instantiate it. How do I instantiate it?
Thanks
In the simplest case, you can just append the initialization directly to your creation of the field:
Some further hints:
Considering that you should usually program to an interface, it is a good practice to declare the variable using a type that is "as basic as possible". You should hardly ever declare a variable as
but basically always only as
because
Mapis the interface that is relevant here.You can also add generics in JCodeModel. These usually involve some calls to
narrowon certain types. It is a bit more effort, but it will generate code that can be compiled without causing warnings due to the raw types.An example is shown here. (It uses
Stringas the key type andIntegeras the value type of the map. You may adjust this accordingly)The generated class looks as follows: