Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exec'ing a string?

 
David Duran
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it possible to execute a string as a line of code? For example:
String code = "System.out.println(\"Hello\");";
Java.exec(code); // == System.out.println("Hello");
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can start a process with Runtime.getRuntime.exec("someComand") but the problem is that it has the same shell as your java program and unless you connect to its output stream and display it from the java program it just dumps its output into sort of a virtual garbage can. If the process fills the output buffer and you don't consume that output from your java program it will lock it up. Now you can use some tricks to open up a different shell, but that is platform dependent. Here's an example for Windows:
hello.bat


ProcessHelloWorld.java
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want to exectute a String as a line of Java code - well, it's possible I guess, if you surrnound it with a token class declaration, and then use exec to compile it and then run it. But I think that's going to be far too much trouble, and it probably won't work very well, and there are various complications I don't want to get into. Michael's example using shell scripting is a step in the right direction. I'd also suggest you might look into Jython, a complete scripting/programming language which can be easily invoked from Java. See this page on embedded Jython for more info.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic