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
.
Asked
Active
Viewed 452 times
0

starwarswii
- 2,187
- 1
- 16
- 19
-
I dnt think its possible bcoz java is compiled by the java compiler and run by JRE – Kick Jan 29 '14 at 14:33
-
http://stackoverflow.com/questions/4389232/run-piece-of-code-contained-in-a-string – jonhopkins Jan 29 '14 at 14:39
3 Answers
1
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.
-
1Netbeans compiles code written by a user. It's pretty popular, and not really that dangerous. – Rainbolt Jan 29 '14 at 14:41
0
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();
}

deed
- 1
0
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!

lance-java
- 25,497
- 4
- 59
- 101