3

I've been experimenting with a tiny kludge of a Dungeons and Dragons combat emulator in Java. It's primarily to allow me to test out my new knowledge, and one way I encourage myself to learn is to push at what I already know. Hence my question: is there a way to execute code input by the user, during runtime? An example -

During an encounter, the user add an extra line to the 'Behaviour' Array of Strings (via a Scanner, most likely). They add:

 "for(Monster m : Room) if(m.getHP()>10) adventurer.attack(m);"

During their 'turn' the program iterates through each String in 'Behaviour', executing the above line of code.

Is something like this possible? Where should I look if it isn't?

Spwack
  • 47
  • 4
  • 1
    Java does not support that. However, there are some JVM based language like Groovy supports – Amit Bera Jun 12 '18 at 16:05
  • Some frameworks support a limted set of operations, like [Spring EL](https://docs.spring.io/spring/docs/4.3.10.RELEASE/spring-framework-reference/html/expressions.html). But there is no eval or simillar in Java – thopaw Jun 12 '18 at 16:08
  • Possible duplicate of [Dynamic code execution](https://stackoverflow.com/questions/4166135/dynamic-code-execution) – Tobias Geiselmann Jun 12 '18 at 16:13
  • If you want to run interpreted codes, write a script. Scripts will not be compiled, but interpreted. You can check Nashorn. – user3437460 Jun 12 '18 at 16:17

3 Answers3

2

Yes that is possible. In fact we can do pretty much everything by programming.

You can use BeanShell for that purpose.

letsintegreat
  • 3,328
  • 4
  • 18
  • 39
0

This can be done in part using the JavaCompiler interface. It needs to compile entire class definitions found in files. Strings as code are not possible.

Java ships with JavaScript engine that can execute code at runtime.

Sid
  • 4,893
  • 14
  • 55
  • 110
0

You may use the Nashorn engine which let you execute JS scripts at runtime, as Nashorn share the JVM you can access some objects from there.

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69