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?

  • 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. – nanofarad Jul 07 '13 at 17:55
  • This previous thread may be helpful on "using eval in Java": http://stackoverflow.com/questions/2605032/using-eval-in-java – Shafik Yaghmour Jul 07 '13 at 17:56

2 Answers2

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/

Dennis Kriechel
  • 3,719
  • 14
  • 40
  • 62
1

You can use BeanSHell or Compiler API

stinepike
  • 54,068
  • 14
  • 92
  • 112