2

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?

2
  • Java does not have any form of eval( statement. You may be able to get away with JVM tricks and low-level access to the classloader. Commented Jul 7, 2013 at 17:55
  • This previous thread may be helpful on "using eval in Java": stackoverflow.com/questions/2605032/using-eval-in-java Commented Jul 7, 2013 at 17:56

2 Answers 2

2

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/

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

Comments

1

You can use BeanSHell or Compiler API

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.