0

Is there a way to do something like the following example implies in Java?

public class HandleCode
{
    public static void main(String[] args)
    {
        String someCode = "System.out.println(aNumber);";

        int aNumber = 123;

        pasteCode(someCode); // Here we somehow tell Java to paste in at pre-compile time the text that is stored in someCode and treat it as source-code text.
    }

    private static void pasteCode(String code)
    {
        // Method code here
    }
}

This hypothetical code would print: 123

Is there such a way to code pasteCode method to do this in Java? I know this is possible to do in C++ thanks to some pre-compiler commands, but I was wondering how this is done in Java.

programmar
  • 670
  • 2
  • 8
  • 18
  • I would write generated code to a .java file at runtime, compile it using ProcessBuilder (https://docs.oracle.com/javase/8/docs/api/java/lang/ProcessBuilder.html), and pass arguments to the program. Is that a feasible option for you? – RuntimeException Nov 30 '15 at 10:35

1 Answers1

1

You can use a ScriptEngine(Manager) to get a JavaScript engine to execute this. However in java, once compiled, the label "someCode" of your string no longer exists.

This link explains how to do it:

https://docs.oracle.com/javase/7/docs/technotes/guides/scripting/programmer_guide/

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80