【发布时间】:2012-04-29 18:59:38
【问题描述】:
朋友们,
我们正在编写一个验证框架...
我们确实有如下配置文件...
<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 循环中执行此操作。
有没有其他方法可以将“< 或在字符串上使用比较运算符?
这样,我的代码会简单,对未来更多的运营商有用。
================================================ ===============================
感谢大家的建议和回答...
我决定使用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"));
返回真/假。
谢谢,祝你好运...
【问题讨论】:
-
你不必使用
if-then-else链,你可以使用哈希映射。但是没有捷径可以动态完成,因此您需要进行大量编码。 -
你也需要'
-
是的,我想涵盖所有可能的比较,例如 、>=、==、!=...等
-
感谢大家的快速回复和许多可能的方法......感谢 Angelo 提出好的框架......
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"));BeanShell's bsh.Interpreter 做了魔法
标签: java dynamic operators conditional-statements primitive