变量必须提供维度表达式或数组初始值设定项错误

时间:2012-02-06 15:19:12

标签: java arrays

出于测试目的,我硬编码了一个bean数组,因此我可以将变量传递给数据库。我现在从表单中提取变量,如果它们不为null,则希望在bean数组中设置它们。我认为我的语法错了。

硬编码:

CriteriaBean[] filters = new CriteriaBean[]
{
    new CriteriaBean("YEAR","=","2012"),
    new CriteriaBean("LOCATION","in","('XXX','YYY')"),
    new CriteriaBean("TOM","is","not null") 
};

我试图做这样的事情并得到错误:

 CriteriaBean[] filters = new CriteriaBean[]
           {
            if (form.getYear() != null) 
            {   
            new CriteriaBean("YEAR","=","2012")
            }


           };

CriteriaBean

public class CriteriaBean
    {
public static final CriteriaBean[] EMPTY_ARRAY = new CriteriaBean[0];

private String fieldName;
private String value;
private String operation;

public CriteriaBean() { } 
public CriteriaBean( String field, 
                              String op, 
                              String val ) 
{
   this.fieldName = field; 
   this.operation = op;
   this.value = val;
}



public String getName() { return this.name; }
public String getOp() { return this.op; }
public String getVal() { return this.val; }

public void setName(String val) { this.name = val; }
public void setOp(String val) { this.op = val; }
public void setVal(String val) { this.val = val; }

有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

关闭!试试这个:

CriteriaBean[] filters = form.getWySelect() == null
    ? new CriteriaBean[] {}
    : new CriteriaBean[] {
        new CriteriaBean("WORKLOAD_YEAR","=","2012")
      };

此代码使用ternary语法根据条件使用备用初始值设定项。