gpt4 book ai didi

java - 使用 MVEL 计算表达式

转载 作者:行者123 更新时间:2023-12-01 12:25:52 24 4
gpt4 key购买 nike

我需要计算 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)

最佳答案

您必须将 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

关于java - 使用 MVEL 计算表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26340300/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com