通过外部提供逻辑对数据集进行动态计算

时间:2013-11-11 07:30:35

标签: java

我正在对数据集进行一些数学运算。根据项目的要求,可以随时更改数学公式/逻辑。所以我想从Java代码中保留这些形式,可能在配置文件中。以下是示例配置文件 -

formula.properties档案 -

formula_a=(a+b)/(7*c+b^2)

formula_b=(a^(1/2)-formula_a*13)

formula_c=spilt_time(formula_b,a,b)

Calculator.java(虚拟Java文件,可能不正确,仅用于演示目的)

public class Calculator
{
    private final static String FORMULA_A = "formula_a";
    private final static String FORMULA_B = "formula_b";
    private final static String FORMULA_C = "formula_c";

    public static void main(String[] args)
    {
        long a = 1738342634L;
        long b = 273562347895L;
        long c = 89346755249L;
        long ansFromFormulaA = applyFormulaFromConfig(FORMULA_A, new long[] { a, b, c });
        long ansFromFormulaB = applyFormulaFromConfig(FORMULA_B, new long[] { a, b, c });
        long ansFromFormulaC = applyFormulaFromConfig(FORMULA_C, new long[] { a, b });
    }

    // spilt_time is used in formula_c
    public static long[] spilt_time(long[] params)
    {
        final long[] split = new long[2];
        // Some logic here which is applied on params array and answer is pushed
        // into split array
        return split;
    }

    private static long applyFormulaFromConfig(String formulaName, long[] params)
    {
        long ans = 0L;
        // Read formula from property file here and apply the params over it and
        // return the answer
        return ans;
    }
}

请帮我设计一个解决方案。

1 个答案:

答案 0 :(得分:1)

好的,这是一个:

使用JavaScript在应用程序外部的单独js文件中定义函数。可能看起来像这样:

function myFunction1(x, y, z) {
  return x * y + z;
}

现在,您可以通过Java ScriptEngine评估这些脚本,并按名称调用这些函数,并将它们传递给您的参数。

看看:http://www.wondee.info/2013/10/30/the-scriptengine-bindings/

编辑:

Propeterties文件:

function1=x + y * z
function2=x * x

将函数读入公式变量......和......

您可以将函数放在String中并将其放在函数体中:

String formula = readFromProperties("function1");

String myFunctionScript = String.format("function myFunction(x, y, z) { return %s ;}", formula);