友
我们正在编写验证框架......
我们确实有如下的配置文件......
<root>
<property name="Premium">
<xmlTag>//Message/Request/Product/Benefit/Premium/amount</xmlTag>
<valueType>float</valueType>
<validation condition=">" value="0">Premium Amount cannot be less than Zero.</validation>
</property>
我使用XPath获取XML值,并通过<valueType>
元素值...
不,我确实已将value="0"
转换为浮动。
现在,我必须应用已指定为condition=">"
的条件。
我不想在IF ELSEIF .... ELSE循环上执行此操作。
还有其他方法可以转换“&lt;”在操作符<
中或在String上使用compare运算符?
通过这种方式,我的代码对于未来的更多运营商来说将是简单且有用的。
=============================================== ==============================
感谢大家的建议和答案...
我决定使用BeanShell的bsh.Interpreter。它为我工作......
示例代码全部...
System.out.println(new bsh.Interpreter().eval("1 < 0"));
System.out.println(new bsh.Interpreter().eval("1 > 0"));
System.out.println(new bsh.Interpreter().eval("1 >= 0"));
System.out.println(new bsh.Interpreter().eval("0 >= 0"));
System.out.println(new bsh.Interpreter().eval("1 != 0"));
System.out.println(new bsh.Interpreter().eval("0 != 0"));
System.out.println(new bsh.Interpreter().eval("1 == 0"));
System.out.println(new bsh.Interpreter().eval("0 == 0"));
返回我的真假。
谢谢&amp;祝你好运......
答案 0 :(得分:2)
您可以使用switch语句
char operator = ...;
switch(operator) {
case '<': return value1 < value2;
case '=': return value1 == value2;
}
答案 1 :(得分:2)
我建议使用表达式语言,例如 Java EL ,或者甚至更好的 Apache Commons Jexl ,因为它更容易集成。以下是从JEXL website获取的代码示例:
// Assuming we have a JexlEngine instance initialized in our class named 'jexl':
// Create an expression object for our calculation
String calculateTax = "((G1 + G2 + G3) * 0.1) + G4";
Expression e = jexl.createExpression( calculateTax );
// populate the context
JexlContext context = new MapContext();
context.set("G1", businessObject.getTotalSales());
context.set("G2", taxManager.getTaxCredit(businessObject.getYear()));
context.set("G3", businessObject.getIntercompanyPayments());
context.set("G4", -taxManager.getAllowances());
// ...
// work it out
Float result = (Float)e.evaluate(context);
在您的特定示例中,您可以将验证XML更改为:
<property name="Premium">
<xmlTag>//Message/Request/Product/Benefit/Premium/amount</xmlTag>
<valueType>float</valueType>
<validation expression="Premium> 0">Premium Amount cannot be less than Zero.</validation>
</property>
然后构建自己的JEXL上下文:
JexlContext context = new MapContext();
context.set("PREMIUM", <Premium value fetched from XML>);
在我看来,这是最具扩展性的解决方案,因为它允许您只用一行代码构建复杂的验证表达式。
答案 2 :(得分:0)
将原始值包装到相应的包装器中:
Float f = new Float(floatValue)
然后,您可以多态地使用提供的compareTo()
方法。
编辑: 您还可以查看表达式解析的全功能实现;除了这里已经提到过的其他内容之外,我还会添加Spring EL。