1

How could I write Java code that is executed like javascript code used together with the eval function?

What I would like to achieve would be something like this:

System.execute ("String str = \"test\"; System.out.println(str);");

which would print the word 'test'. (10x dehmann )

A code sample would help a lot.

  • It might just be me, but your question doesn't make a lot of sense. JavaScript is a Web Scripting language, where as java is run in the java framework. You can build java applets, but I don't think that's what you're referring to. – regex Feb 25 '09 at 22:42
  • 1
    I'm guessing the reference to JavaScript was just an example of what he wants to achieve. – Michael Myers Feb 25 '09 at 22:43
  • I think he wants something like: System.execute("String str(\"test\"); System.out.println(str);"); which would print the word 'test'. – Frank Feb 25 '09 at 23:42
  • possible duplicate of [Is there an eval() function in Java?](http://stackoverflow.com/questions/2605032/is-there-an-eval-function-in-java) – Raedwald Dec 10 '14 at 13:10

4 Answers4

4

Look into BeanShell or Groovy. Both will give you reasonable solutions--but those solutions rely on my interpretation of your problem, which may be flawed.

Bill K
  • 62,186
  • 18
  • 105
  • 157
1

I've used the JavaScript engine shipped with Java 6 and it works quite well. The performance of the engine is very very decent.

Check the page http://java.sun.com/javase/6/docs/technotes/guides/scripting/programmer_guide/index.html

Ravi Wallau
  • 10,416
  • 2
  • 25
  • 34
1

I believe the compiler API is present in the current Java SE 6. See the javadoc.

See this blog post for details and an example.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
0

For completeness sake, the Compiler API is coming in the next version of Java..

Tim Williscroft
  • 3,705
  • 24
  • 37
  • The Compiler API is in Java 6. It works but its ugly to use. However you can use BeanShell and JCI if you don't have Java 6. – Peter Lawrey Feb 26 '09 at 19:55