Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to execute code from String during runtime?

Tags:

java

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?

like image 595
Spwack Avatar asked Feb 02 '26 23:02

Spwack


1 Answers

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

You can use BeanShell for that purpose.

like image 54
Letsintegreat Avatar answered Feb 04 '26 13:02

Letsintegreat