0

Possible Duplicate:
Executing java code given in a text file
using eval in Java

I have written a Java program, and I was wondering if I can do Java in a String. For example, let's say I have the following:

String s = "int i = 1;";

In the String above, I have a Java command in it. Can I execute the Command outside the String in my actual program?

Community
  • 1
  • 1
  • 2
    "I'm afraid I can't let you do that" - Hal – gtgaxiola Sep 18 '12 at 20:22
  • This question is answered in the following question: http://stackoverflow.com/questions/935175/convert-string-to-code – ajon Sep 18 '12 at 20:23
  • I'd say, yes & no. Yes you can do dynamic compilation, but, probably not the way you're trying (I'd be happy to be wrong). Take a read through [Generating Java classes dynamically through Java compiler API](http://www.accordess.com/wpblog/an-overview-of-java-compilation-api-jsr-199/) to start with (first link off Google) – MadProgrammer Sep 18 '12 at 20:25
  • Why do you need that? Are you forced to work with Java? Maybe a dynamic language supporting eval is what you are looking for, even though I discourage doing something like that as it makes your code much harder to understand and maintain – mariosangiorgio Sep 18 '12 at 20:28

3 Answers3

3

You would be able to do this with something like BeanShell.

Tim Bender
  • 20,112
  • 2
  • 49
  • 58
1

No, you cannot enter code into a String like that. The " symbol essentially delimits the real code from a String.

Once you type in String xyz = you are creating a variable, and what comes next needs to be a STring value. Maybe later you can do something with that, but as of now it's not execcutable

You might like to brush up on Strings:

Java String Class

Quotation marks inside a string

Community
  • 1
  • 1
Caffeinated
  • 11,982
  • 40
  • 122
  • 216
1

While parsing Java like that might be tricky you could use something like Rhino to evaluate JavaScript in a string. This might be a bit outside of what you are asking though.

Community
  • 1
  • 1
Jason Sperske
  • 29,816
  • 8
  • 73
  • 124