0

I want to know if there is any way to convert a String to Java compilable code...

For example, I have the following code:

public int calcSum(int a, int b) {
    return a+b;
}

public int calcDifference(int a, int b) {
    return a-b;
}

and I have:

String code = "System.out.println(this.calcSum(50, 50));\n"
            + "System.out.println(this.calcDifference(80, 40));";

after running the "code", the console display:

100
40

it is possible to do this?

  • No, Java won't let you do that inline like that. You might, with some difficulty, invoke the Java compiler and then shell out to the Java VM, but that's probably as close as it gets. You can run a Java*script* engine at runtime, though. – Louis Wasserman Jun 19 '15 at 23:01
  • @LouisWasserman Actual Java has a JavaCompiler class which would allow you to do this via code (no shell required), but no, not in memory, you'd gave to compile the class to a File first then use a classloader to load the file. Personally, I'd not recommend it, but that's me – MadProgrammer Jun 19 '15 at 23:17

0 Answers0