0

I'm creating a software that would execute custom code line by string SO, is there any method function or whatever you want that can do that :

String command="println("the TEST work !!!")";
magicExecMethod(command);

*and it print : the TEST work !!!

Thancks

AlexR
  • 114,158
  • 16
  • 130
  • 208
hugodecasta
  • 262
  • 4
  • 13
  • You can use some scripting languages within java, but java is a compiled language (compiled into byte code) and you can't expect it to be happy with that sort of thing – Richard Tingle Oct 16 '13 at 16:39
  • See [this](http://stackoverflow.com/a/7487938/2187042) for all your scripting needs; the example is using javascript within java – Richard Tingle Oct 16 '13 at 16:40
  • Well nobody else here seems to think so, but there is a way already. You would need a skeleton String, one that specifies the main method in Java. Then, add the command into the skeleton at the right spot, save it as a .java and compile it (easy to do if you have JDK and access to JavaCompiler). Then, use reflection to invoke it. Should you do this though? No. – Obicere Oct 16 '13 at 16:41
  • @Obicere Would this work on a computer with only the JRE, not a JDK? I mean of course you can create text files programatically and run command line arguments, but if it doesn't actually work on anyone elses computer does it count – Richard Tingle Oct 16 '13 at 16:42
  • You would need to provide a compiler. Either an online, custom or JDK compiler. – Obicere Oct 16 '13 at 16:43
  • His question is is there something that will make it work. There are all sorts of ways to make valid java source compile at runtime but that statement is not valid java.. It has no containing class or method or static. – Nathaniel Johnson Oct 16 '13 at 17:23

1 Answers1

1

You have several ways to achieve this.

You can create java file by printing it line-by-line, then compile it by either invocation of compiler from command line or by calling java.lang.Compiler, then run it.

Other way is to run your line directly using Groovy - java based language that supports Java syntax and can be used in interpreter mode.

If you are not sticky to java syntax and for example can use java script instead you can use ScriptingHost and Rhino that is a part of JDK since java 1.5.

AlexR
  • 114,158
  • 16
  • 130
  • 208