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?

4
  • 2
    "I'm afraid I can't let you do that" - Hal Commented Sep 18, 2012 at 20:22
  • This question is answered in the following question: stackoverflow.com/questions/935175/convert-string-to-code Commented Sep 18, 2012 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 to start with (first link off Google) Commented Sep 18, 2012 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 Commented Sep 18, 2012 at 20:28

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

I agree, +1. Much safer than compiling and running using the compiler API
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.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.