4

We have discussed how java is first compiled into Java bytecode and then interpreted by the JVM. Build into the program we are using (Dr Java), there is a panel called Interactions where you can type code in real time and have it be interpreted and ran (I believe that is how it works). I was wondering if it was possible to have a compiled program in java be ran, and then allow a user to input java code to be interpreted to modify the things that happen. I can't really think of any practical uses of this, but here is an example to clarify:

User runs a program and an integer in initialized with the value of 2 and the name of changeNumber. A pop-up comes up allowing the user to input some java code. They can input something like - "changeNumber = changeNumber + 2;" and have the code execute in real time where if you ended up printing out changeNumber, you would get 4.

Zo72
  • 14,593
  • 17
  • 71
  • 103
Phiction
  • 2,387
  • 2
  • 12
  • 7
  • 1
    The simplest answer that comes into my mind is: take a look at **Groovy**: http://groovy.codehaus.org/. It's a Java language extension which inherently allows what you are looking for. – Jack Sep 18 '13 at 17:38
  • Some debuggers will allow you to update some values. – PM 77-1 Sep 18 '13 at 17:39
  • 1
    Sure, parse the input and add a touch of reflection. I wouldn't advise you to look into this just yet though. – Jeroen Vannevel Sep 18 '13 at 17:40
  • possible duplicate of [Runtime code generation and compilation](http://stackoverflow.com/questions/4064226/runtime-code-generation-and-compilation) – om-nom-nom Sep 18 '13 at 17:49

1 Answers1

3

This is possible using the Reflection API.

As a side note, I do not understand the downvotes. This is a good and well-written question for a beginner.

Uku Loskit
  • 40,868
  • 9
  • 92
  • 93
  • Personally, I have downvoted this question because it lacks any research effort -- there are tons of resources in the internet on the topic, e.g. **first result** in google with query *java runtime code* leads [to this stackoverflow question](http://stackoverflow.com/questions/4064226/runtime-code-generation-and-compilation) – om-nom-nom Sep 18 '13 at 17:49