我需要在包含日期的MVEL中评估表达式。基本上,我需要在给定日期添加一定天数并获取值。当我尝试在MVEL中评估表达式时,获得一些例外。
这是我的代码::
package Mvel;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.mvel2.MVEL;
import org.mvel2.integration.VariableResolverFactory;
import org.mvel2.integration.impl.MapVariableResolverFactory;
public class Mveldatetest {
public static void main(String[] args) throws ParseException {
// TODO Auto-generated method stub
Map<String, Object> m1 = new HashMap<String, Object>();
m1.put("name", "xyz");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date d1 = sdf.parse("02/10/2014");
m1.put("doj", d1);
//Date d2=sdf.parse("05/10/2014");
System.out.println("Given Date"+" "+d1);
final Calendar c = Calendar.getInstance();
c.setTime(d1);
System.out.println(c.getTime());
Date finaldate=(Date) MVEL.eval("c.add(Calendar.DAY_OF_MONTH, 4)",m1);
System.out.println(finaldate);
}
}
我收到以下异常::
Exception in thread "main" [Error: unresolvable property or identifier: c]
[Near : {... c.add(Calendar.DAY_OF_MONTH, 4 ....}]
^
[Line: 1, Column: 1]
at org.mvel2.PropertyAccessor.getBeanProperty(PropertyAccessor.java:677)
at org.mvel2.PropertyAccessor.getNormal(PropertyAccessor.java:179)
at org.mvel2.PropertyAccessor.get(PropertyAccessor.java:146)
at org.mvel2.PropertyAccessor.get(PropertyAccessor.java:126)
at org.mvel2.ast.ASTNode.getReducedValue(ASTNode.java:187)
at org.mvel2.MVELInterpretedRuntime.parseAndExecuteInterpreted(MVELInterpretedRuntime.java:106)
at org.mvel2.MVELInterpretedRuntime.parse(MVELInterpretedRuntime.java:49)
at org.mvel2.MVEL.eval(MVEL.java:165)
at Mvel.Mveldatetest.main(Mveldatetest.java:31)
答案 0 :(得分:1)
您必须将c
添加到上下文m1
。此外,Calender
也是未知的,但您可以使用c
代替(丑陋,但有效)。最后,请注意add
返回void,即它就地修改c
。试试这个:
System.out.println(c.getTime());
m1.put("c", c);
MVEL.eval("c.add(c.DAY_OF_MONTH, 4)", m1);
System.out.println(c.getTime());
输出:
Thu Oct 02 00:00:00 CEST 2014
Mon Oct 06 00:00:00 CEST 2014