简体   繁体   English

基于Java的表达式评估器

[英]Java Based Expression Evaluator

I need an Expression Evaluator that can allow me to evaluate an expression such as follows: 我需要一个表达式评估器,它可以让我评估如下表达式:

(ItemWeight + PackageWeight) * 2

So, given the following Input: 因此,给定以下输入:

ItemWeight = new Weight(2.0, LBS);
PackageWeight = new Weight(0.2, LBS);

Output would be: Weight(4.4, LBS) 输出为: Weight(4.4, LBS)

public class Weight {
   private final float value;
   private final Unit unit;

   public float getValue() { return value; }
   public Unit getUnit() { return unit; }

   public enum Unit {
       LB, KG, GRAMS;
   }
}

Similarly, I'd like to add/subtract two Amount objects (where amount is made up of a value and currency symbol). 同样,我想添加/减去两个Amount对象(其中,金额由值和货币符号组成)。

Note: It is OK in my use case to assume that two values that do not have the same unit cannot be added/subtracted, etc 注意:在我的用例中,可以假定不能将两个不具有相同单位的值加/减,等等

I read about MVEL, but it didn't seem like MVEL would be able to handle arithmetic expressions involving POJOs. 我了解了MVEL,但似乎MVEL不能处理涉及POJO的算术表达式。 Other options that came to mind are Rhino and Commons EL. 想到的其他选项是Rhino和Commons EL。

What would be a good library that I can use (and if needed extend) for solving this problem? 我可以使用(如果需要扩展)一个好的库来解决此问题吗?

Thanks! 谢谢!

Java isn't C++; Java不是C ++。 you can't overload operators. 您不能重载运算符。

It might not be quite as visually appealing to do it using a fluent interface, but I would say it's easier than what you're proposing. 使用流畅的界面在视觉上可能并不那么吸引人,但是我想说这比您提出的要容易。

This is interesting, because you're going to have to think about more than just EL. 这很有趣,因为您将需要考虑的不仅仅是EL。 The idea is far more general than your Weight class. 这个想法比您的Weight班要笼统得多。 It's more like QuantityWithUnits . 它更像QuantityWithUnits Here are a few of the questions you'll have to answer: 以下是您必须回答的一些问题:

  1. How will you prohibit addition and subtraction operations on objects with differing units? 您将如何禁止对具有不同单位的对象进行加减运算?
  2. How will you account for creating new units when you divide and multiply? 除法和乘法时,如何计算新单位?
  3. Will you allow scalar multiplication and division? 您将允许标量乘法和除法吗?
  4. Will you disallow addition of scalars to quantities with units? 您是否会禁止在单位数量中添加标量? Or will you silently create new objects with like units behind the scenes? 还是您会在幕后悄悄地创建具有类似单位的新对象?
  5. Will you have other common physics operations like powers? 您还会进行其他常见的物理运算,例如幂运算吗?
  6. How will you work with systems of units and conversions? 您将如何使用单位和转换系统?

You may think "I'm too clever for all that; I just want to do something 'simple and practical'", but eventually you'll have to answer all these. 您可能会认为“我对所有这些都太聪明了;我只想做一些“简单实用”的事情,但是最终您必须回答所有这些问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM