-6

Possible Duplicate:
Convert String to code
Run piece of code contained in a String

is there any way to turn a variable(string) into to a piece of code? My string has to be changeable (non-static) If you can explain it simply that would be nice :D

Community
  • 1
  • 1
Neobonde
  • 85
  • 2
  • 7
  • 1
    execute a String as if it is Java-code? No, it is not possible. – Nikolay Kuznetsov Dec 19 '12 at 11:02
  • Not clear, please give more info – Aviram Segal Dec 19 '12 at 11:02
  • what u want to do explain a bit more – Nipun Jain Dec 19 '12 at 11:03
  • `static` strings can change, too. You mean non-`final`. It's possible, but not easy. Search for [Java Compiler API](http://mike-java.blogspot.de/2008/03/java-6-compiler-api-tutorial.html) – jlordo Dec 19 '12 at 11:03
  • @Neobonde please always provide an example, it's worth the effort. Do you want to do something like this: `String commands = "int foo = 42; System.out.println(foo);";` and than execute the _code_ within the string? – jlordo Dec 19 '12 at 11:08
  • Once more, I'd point to the [Java Scripting API](http://docs.oracle.com/javase/6/docs/technotes/guides/scripting/programmer_guide/index.html) for that use case. – JimmyB Dec 19 '12 at 12:51

1 Answers1

2

I assume, that you want to create a String object with some Java statements and execute the content as if it was a method.

No, it is not possible, because that would imply, that java was an interpreted programming language. Which is not the case.

You could merge the line with some sort of class template (on another string), store it to a file, compile that using the jdk (call javac with `Runtime.exec) and load the class with a custom classloader, then reflect the method and hope for the best.

There is a rather complicated way using the fairly new Java Compiler API, but I guess, that is far beyond your needs. (And there have to be some more complicated tricks, because the eclipse IDE provides views that allow executing Java statements.)

Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268