Question

I am wondering if there is a way in java to accept java code as user input, and then run it. For example, the user could type in:System.out.println(someMethod.toString());and it would print out the output from someMethod.

Was it helpful?

Solution

It can be very dangerous to compile random code written by the user. But you can try using the Java Compiler API, or if you want something similar but not strictly java use groovy then (it is easier to to watch you want with the GroovyShell object)

I haven't tried to do something like this myself, but i found some useful answers here: Convert String to Code

Be very careful if you succeed.

OTHER TIPS

I dont really know if you can convert user input to runnable code, but you could make the program accept words that are connected to methods.

if(input == someMethod)
{
   someMethod();
}

Take a look at beanshell which can interprit a java string and run the commands.

But be very careful. Giving access to this opens up a HUGE security hole!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top