我需要初始化如下的二维数组
Object[][] someName = {
{"param1","param2","param3"},
{"param4","param5","param6"}
};
我尝试过
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);
但是它会启动一维数组,
感谢您的帮助
答案 0 :(得分:1)
可能不完全相同,但是以下代码初始化示例2d数组:
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);
这将生成以下内容,并显式声明内部数组:
public class TestClass {
public void runme() {
Object[][] someName = new String[][] {new String[] {"param1", "param2", "param3"}, new String[] {"param4", "param5", "param6"}};
}
}
您尝试的代码几乎是正确的,您只需要在newArray()
调用中声明数组:JExpr.newArray(codeModel.ref(String.class).array())