This week's book giveaway is in the General Computing forum.
We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line!
See this thread for details.
The moose likes Java in General and the fly likes Running code written in a string Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Running code written in a string" Watch "Running code written in a string" New topic
Author

Running code written in a string

colin shuker
Ranch Hand

Joined: Apr 11, 2005
Posts: 712
Hi,

I heard in Java 6, it was possibly to write code in a String, then execute it, eg:

Is this possible?
Thanks
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 16811
    
  19

Is this possible?


It depends.... You have two options (which are close, but requires work).

You can use the "java scripting api", which allows you to call out to scripting engines. By default, it only supports Javascript, which is close, but isn't exactly Java. However, you can load drivers for it, and there does seem to be some that "look and feel" like java.

You can use the "java compiler api", which allows you to compile java. So, you can use it to compile and run dynamically generated code.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Nitesh Kant
Bartender

Joined: Feb 25, 2007
Posts: 1638

Java Scripting api provide supports for third party JSR 223 implementations. Jython provides a JSR 223 implementation and hence can be executed using the JDK apis.
Jython can also execute java code, so this means the example you have given can be executed. For more information look here


apigee, a better way to API!
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Running code written in a string
 
Similar Threads
java.lang.StringIndexOutOfBoundsException: String index out of range: -2
How many String Objects
a simple question
Doubt in EL
Total number of object string creates?