lundi 27 juillet 2015

Dynamically create and compile a function in Java 8

I have a Java program that generates a mathematical equation based on user input. I'd like to evaluate the equation, but iterating over its syntax tree is rather slow. A faster solution is to put the equation in a Java file, compile it, and call the compiled code (during runtime). Here is what I am currently doing:

  • Create an Equation.java file with the function as a static member. For example, if the equation generated is 3*x + 2*y (the real equation is much more complicated), the program would create the file

    public class Equation {
        public static DoubleBinaryOperator equation = (x, y) -> 3*x + 2*y;
    }
    
    
  • Compile it into Equation.class using JavaCompiler
  • Dynamically import the class file and call the equation using reflection

This is an enormous amount of boilerplate for something that seems like it should be simple. Is there an easier way of turning this equation into a function and calling it at runtime?





Aucun commentaire:

Enregistrer un commentaire