如何在Java中将String转换为Function? [英] How to convert String to Function in Java?

查看:1104
本文介绍了如何在Java中将String转换为Function?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在stackoverflow上有一个类似相同标题的问题这里,但我想问一下是否有可能在Java中做类似的事情。

There is a question with the same title like this on stackoverflow here, but I wanted to ask if it is possible to do something similar to this in Java.

我想做一些类似于desmos的东西,就像那个人在Javascript中做的那样,但我想用Java来使用lwjgl 2.我是Java的新手我想知道是否可以将一段字符串转换为方法。有可能吗?

I wanted to make something similar to desmos, just like that guy did in Javascript,but i want to make it in Java using lwjgl 2. I am new to Java and I'd like to know if it is possible to convert a piece of string into a method. Is it possible?

我找了可能的选项,我发现你可以制作自己的Java eval()方法。但我不想为窗口宽度的每个像素替换字符串中的 x

I have looked for possible options and I found out that your can make your own Java eval() method. But I don't want to replace the x in the string for every pixel of the window-width.

在此先感谢。

推荐答案

您需要的是一个可以计算表达式的引擎/库,在执行时定义为字符串。如果将评估代码包装到函数调用中(例如lambda函数),您将得到所需的内容。

What you need is an engine/library that can evaluate expressions, defined as string at execution time. If you wrap the evaluation code into function call (e.g. lambda function), you will get what you need.

选项1:您可以使用 exp4j exp4j 是一个小型脚本库,能够在执行时评估表达式和函数。这是一个例子:

Option 1: You can use exp4j. exp4j is a small footprint library, capable of evaluating expressions and functions at execution time. Here is an example:

Expression e = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)")
        .variables("x", "y")
        .build()
        .setVariable("x", 2.3)
        .setVariable("y", 3.14);
double result = e.evaluate();

选项2:您可以使用 Java的脚本引擎。您可以使用它来计算定义的表达式,例如,在JavaScript中:

Option 2: You can use the Java's script engine. You can use it to evaluate expressions defined, for example, in JavaScript:

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
Object result = engine.eval("sin(1.25)");

选项3:编译为本机Java。使用此方法,您可以使用模板生成包含表达式的类的.java文件。比你调用Java编译器。这种方法的缺点是在实现中有一些复杂性和一些初始延迟(直到编译类),但性能是最好的。以下是一些探索链接:

Option 3: Compile to native Java. With this approach, you use template to generate .java file with a class that contains your expression. Than you call the Java compiler. This approach has the drawback that has some complexity in the implementation and some initial latency (until the class is compiled), but the performance is the best. Here are some links to explore:

  • Create dynamic applications with javax.tools
  • In particular javax.tools.Compiler

注意事项无论您选择何种方法,请记住您需要考虑安全性。允许用户输入可以在没有安全限制的情况下进行评估的代码可能非常危险。

Note of Caution Whatever approach you chose, have in mind that you need to think about the security. Allowing the user to enter code which can be evaluated without security restrictions could be very dangerous.

这篇关于如何在Java中将String转换为Function?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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