我能严格评估存储在Java中的字符串中的布尔前pression? [英] Can I strictly evaluate a boolean expression stored as a string in Java?

查看:210
本文介绍了我能严格评估存储在Java中的字符串中的布尔前pression?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够评估存储为字符串的布尔前pression,如下所示:

I would like to be able to evaluate an boolean expression stored as a string, like the following:

"hello" == "goodbye" && 100 < 101

我知道有吨对这样的问题,以便了,但我问这一个,因为我试过最常见的回答这个问题,的 BeanShell的,它允许语句像这样的评价

I know that there are tons of questions like this on SO already, but I'm asking this one because I've tried the most common answer to this question, BeanShell, and it allows for the evaluation of statements like this one

"hello" == 100

没有麻烦。有谁知道一个自由和开放源码解析器抛出错误的东西像操作数不匹配?或者有没有在BeanShell中的设置,这将帮助我吗?我已经尝试过国米preter.setStrictJava(真)。

with no trouble at all. Does anyone know of a FOSS parser that throws errors for things like operand mismatch? Or is there a setting in BeanShell that will help me out? I've already tried Interpreter.setStrictJava(true).

为了完整起见,这里的code,我使用目前:

For completeness sake, here's the code that I'm using currently:

Interpreter interpreter = new Interpreter();
interpreter.setStrictJava(true);    
String testableCondition = "100 == \"hello\"";
try {
    interpreter.eval("boolean result = ("+ testableCondition + ")");
    System.out.println("result: "+interpreter.get("result"));
    if(interpreter.get("result") == null){
        throw new ValidationFailure("Result was null");
    }
} catch (EvalError e) {
    e.printStackTrace();
    throw new ValidationFailure("Eval error while parsing the condition");
}

编辑:

在code我目前返回此输出

The code I have currently returns this output

result: false

没有错误。我想什么做的是抛出的EvalError或的东西的让我知道,有不匹配的操作数。

without error. What I would like it to do is throw an EvalError or something letting me know that there were mismatched operands.

推荐答案

在Java 6中,可以动态调用编译器,在这篇文章中解释道:

In Java 6, you can dynamically invoke the compiler, as explained in this article:

http://www.ibm.com/developerworks/的Java /库/ J-jcomp / index.html的

您可以使用它来动态编译你的前pression到Java类中,如果您尝试将字符串比较了许多这将抛出类型错误。

You could use this to dynamically compile your expression into a Java class, which will throw type errors if you try to compare a string to a number.

这篇关于我能严格评估存储在Java中的字符串中的布尔前pression?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆