2

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.

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?

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.

Thanks in advance.

1 Answer 1

7

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.

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();

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)");

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:

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.

Sign up to request clarification or add additional context in comments.

3 Comments

You can extend Option 3 with bytecode generation - either compile-time (with some build tool plugin) or in runtime.
thank you so much for your help. Can you pls post a link on how I could use the third option. It seems to be quite interesting.
@odermark, added the links to the response. I think the first should give you good start.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.