Connecting Tech Pros Worldwide Forums | Help | Site Map

Run/Execute Code in a String Variable

Newbie
 
Join Date: Jul 2007
Posts: 3
#1: Aug 15 '07
Hi everyone,

I wanted to know if there is a way to execute code that is inside a string variable. If anyone know, please help as I am new to Java.

Thanks..

Lives Here
 
Join Date: Sep 2006
Posts: 12,070
#2: Aug 15 '07

re: Run/Execute Code in a String Variable


Quote:

Originally Posted by gautam89

Hi everyone,

I wanted to know if there is a way to execute code that is inside a string variable. If anyone know, please help as I am new to Java.

Thanks..

For Java code to be executed, it has to be compiled into a .class first.
You could write code that stores that string variable as a .java file, then compile it and run it using Runtime.exec.
JosAH's Avatar
Expert
 
Join Date: Mar 2007
Posts: 10,611
#3: Aug 15 '07

re: Run/Execute Code in a String Variable


... also, have a look at BeanShell which is
an almost Java 1.5 interpreter with a lot of very interesting features.

Also, also, not many people are aware of it but Java 1.6 comes with an entire
Javascript interpreter built-in. Check out the general ScriptEngine framework.

kind regards,

Jos
Newbie
 
Join Date: Jul 2007
Posts: 3
#4: Aug 15 '07

re: Run/Execute Code in a String Variable


Thanks for your help. It makes more sense now why it is difficult to do such a thing.

Perhaps there is another solution around the problem. I need to create two applications (server & client) for an internet cafe management system.

I was planning on the server application to have a 'node' class. In essence, it would create an object for each node/client computer that exists.

I need to be able to call certain methods of any set of node objects on the fly. For example, turn off computers 1, 12, & 22. I don't want to use multiple select case to solve this problem as it will require lots of coding.

Any suggestions?
JosAH's Avatar
Expert
 
Join Date: Mar 2007
Posts: 10,611
#5: Aug 15 '07

re: Run/Execute Code in a String Variable


Quote:

Originally Posted by gautam89

Thanks for your help. It makes more sense now why it is difficult to do such a thing.

It isn't difficult if you know something about parsing expressions. Really it isn't.

Quote:

Originally Posted by gautam89

Any suggestions?

Yep, you might have a look at the Compiler article series in the Java Articles
section. (see the blue menu bar near the top of this page).

kind regards,

Jos
Reply