How to initialise a 2D array using CodeModel

狂风中的少年 提交于 2019-12-20 06:02:32

问题


I need to initialise a 2d array like below

     Object[][] someName = {
                             {"param1","param2","param3"}, 
                             {"param4","param5","param6"}
                            };

I tried like

    JExpression exp = JExpr.newArray(codeModel.ref(String.class)).add(JExpr.lit("param1").add(JExpr.lit("param2"));

    methodBlock.decl(JMod.NONE, codeModel.ref(Object.class).array().array(), dataProviderName, exp);

but it initilases 1d array,

any help is appreciated


回答1:


It might not be exactly the same, but the following code initializes the example 2d array:

JDefinedClass testClass = codeModel._class("TestClass");

JMethod runme = testClass.method(JMod.PUBLIC, codeModel.VOID, "runme");
JBlock methodBlock = runme.body();

JExpression exp = JExpr.newArray(codeModel.ref(String.class).array())
    .add(JExpr.newArray(codeModel.ref(String.class))
                        .add(JExpr.lit("param1")).add(JExpr.lit("param2")).add(JExpr.lit("param3")))
    .add(JExpr.newArray(codeModel.ref(String.class))
                        .add(JExpr.lit("param4")).add(JExpr.lit("param5")).add(JExpr.lit("param6")));

methodBlock.decl(JMod.NONE, codeModel.ref(Object.class).array().array(), "someName", exp);

This generates the following, which explicitly declares the inner arrays:

public class TestClass {


    public void runme() {
        Object[][] someName = new String[][] {new String[] {"param1", "param2", "param3"}, new String[] {"param4", "param5", "param6"}};
    }

}

The code you tried was almost correct, you just needed to declare the array within the newArray() call: JExpr.newArray(codeModel.ref(String.class).array())



来源:https://stackoverflow.com/questions/55790450/how-to-initialise-a-2d-array-using-codemodel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!