John D John D - 28 days ago 8
Java Question

Execute code from a String in Java

I've done some searching, and it seems a few people have asked similar questions, but none of them were quite what I was looking for (some suggested some scripting stuff but i didn't have enough knowledge of what i was doing so i want to use java only if possible).

I need to be able to read lines of code from a String, and then execute them in Java (like this):

String code = "System.out.println("Test code");";

A lot of people reading this might ask why don't you just

System.out.println("Test code");

but I want to execute code other than the println method from Strings.

Is this possible?

Answer Source

If I understand correct, you want to input a string into the java console. This given string then should be magically be typed-in in an external program. If I did not understand correct, I'll remove that answer again.

public class Test {

    public static void main(String[] args) throws IOException, ClassNotFoundException, Exception {
    Robot robot = new Robot();
    String text = "Hello";
    File file = File.createTempFile("tmp", ".txt");

    if (Desktop.isDesktopSupported()) {
    } else {
        // dunno, up to you to handle this
    for (char c : text.toCharArray()) {
        int keyEvent = KeyEvent.getExtendedKeyCodeForChar(c);

If you run this basic code, notepad should open and the text Hello is getting typed. That's what I've prepared for you. Now what you need to do is using a Scanner to get the string from the console instead from a static string.