user1483552
user1483552

Reputation: 99

String acting as code - Java

I'm trying to give the user the option to write one line of code in my program. Their input is saved as a String and I need that string to transfer into a line of code in the eclipse IDE. For example:

String a = "System.out.println("String code test.");"

Now I need this String to compile into the program and print out the text. Is their a way to do this considering when the user inputs the line of code the program has already compiled and therefore cannot insert a new line of code?

I know this question is sort of confusing but if anyone can understand this post or had a similar problem, I would enjoy hearing feedback.

EDIT: I have realized that I might be able to use a BufferedWriter to write to a .java file and then just call that class after it has been writen. Can you write to .java files using BufferedWriter?

Upvotes: 2

Views: 90

Answers (2)

Dennis Kriechel
Dennis Kriechel

Reputation: 3749

It's possible to compile a class in Java at runtime. This means you need to put the code line into a seperate java class file and compile this one. You can find an explanation here:

http://java-bytes.blogspot.de/2012/03/compile-java-files-at-runtime.html

Here is another article I found about dynamic code in java:

http://extremejava.tpk.com.br/2008/11/06/dynamic-code-in-java-aka-eval-in-java/

Upvotes: 2

stinepike
stinepike

Reputation: 54672

You can use BeanSHell or Compiler API

Upvotes: 1

Related Questions