0

Is there a way to run a string as code? I mean if I had a string run having value System.out.println("Hello World) could I run the string as normal code the then output will be Hello World?

For Example:

String code = "System.out.println("Hello World)";

code.run(); //I know this doesn't work

Console:

Hello World
gprathour
  • 14,813
  • 5
  • 66
  • 90
Typo
  • 23
  • 1
  • 6
  • 1
    Checkout my answer here http://stackoverflow.com/a/8364016/782719 – GETah Jul 10 '14 at 00:47
  • I don't want to compile a program I would like to run the String in the current – Typo Jul 10 '14 at 00:50
  • Even if `eval()` was in Java, this won't work. "Hello World" was not enclosed as a literal, you're missing a `"`. It will fail to compile for the syntax error then. Also, you forgot to escape the `"`s within the string. – Unihedron Jul 10 '14 at 01:06
  • 1
    Technically, anytime you compile a java file to a class, you are running a string as code. If you want to import a text file programatically and run it as code from your code, you would have to find a way to recompile it programmatically. I don't know if that is possible – Joshua Zollinger Jul 10 '14 at 01:27

1 Answers1

1

You want the equivalent of JavaScript's eval. There is no equivalent in Java.

Well, there is but it's not trivial.

You can generate the full source code of a class containing that code. Something like

public class StuffToDynamicallyCompile  {
   public static final void main(String[] ignored)  {
       PUT STUFF HERE!
   }
}

And then programatically invoke the compiler, as described in this answer, or as stated in the comments: How to compile .java file from within java program

Not a simple task. Perhaps there's a way to minimize your requirements, so you can allow an extremely limited set of commands, and just execute it with a switch ("if 'dothis' then call doThis(), else if 'doThat', call doThat(), etc.).

Community
  • 1
  • 1
aliteralmind
  • 19,847
  • 17
  • 77
  • 108