Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run code from a string in Java [duplicate]

Tags:

java

For debug reasons, I want to be able to run code that is typed in through the console. For example:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true){
    String str = br.readLine(); //This can return 'a = 5;','b = "Text";' or 'pckg.example.MyClass.run(5);'
    if(str == null)
        return;
    runCode(str); //How would I do this?
}
like image 905
PureGero Avatar asked Jul 12 '13 06:07

PureGero


People also ask

How do you duplicate a string in Java?

To make a copy of a string, we can use the built-in new String() constructor in Java. Similarly, we can also copy it by assigning a string to the new variable, because strings are immutable objects in Java.

How do you run a piece of code in Java?

Type 'javac MyFirstJavaProgram. java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption: The path variable is set). Now, type ' java MyFirstJavaProgram ' to run your program.

How do you repeat a line in Java?

What you want to do is use a nested for loop (i.e. a loop inside a loop). The outer loop will print line by line by first printing the string, then starting new line. A new line is added by System. out.

How do you repeat a string and time in Java 8?

repeated = new String(new char[n]). replace("\0", s); Where n is the number of times you want to repeat the string and s is the string to repeat.


1 Answers

PLEASE DON'T ACTUALLY USE THIS

I was under the assumption you wanted to evaluate a string as Java code, not some scripting engine like Javascript, so I created this on a whim after reading this, using the compiler API mark mentioned. It's probably very bad practice but it (somewhat) works like you wanted it to. I doubt it'll be much use in debugging since it runs the code in the context of a new class. Sample usage is included at the bottom.

import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;

public class main {
    public static void runCode(String s) throws Exception{
        JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager sjfm = jc.getStandardFileManager(null, null, null);
        File jf = new File("test.java"); //create file in current working directory
        PrintWriter pw = new PrintWriter(jf);
        pw.println("public class test {public static void main(){"+s+"}}");
        pw.close();
        Iterable fO = sjfm.getJavaFileObjects(jf);
        if(!jc.getTask(null,sjfm,null,null,null,fO).call()) { //compile the code
            throw new Exception("compilation failed");
        }
        URL[] urls = new URL[]{new File("").toURI().toURL()}; //use current working directory
        URLClassLoader ucl = new URLClassLoader(urls);
        Object o= ucl.loadClass("test").newInstance();
        o.getClass().getMethod("main").invoke(o);

    }
    public static void main(String[] args) {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        while(true){
            try {
            String str = br.readLine(); //This can return 'a = 5;','b = "Text";' or 'pckg.example.MyClass.run(5);'
            if(str == null)
                return;

            runCode(str); //How would I do this?
            } catch(Exception e) {
                e.printStackTrace();
            }
        }

    }
}
//command line
>  System.out.println("hello");
hello
>  System.out.println(3+2+3+4+5+2);
19
>  for(int i = 0; i < 10; i++) {System.out.println(i);}
0
1
2
3
4
5
6
7
8
9

With the SimpleJavaFileObject you could actually avoid using a file, as shown here, but the syntax seems a bit cumbersome so I just opted for a file in the current working directory.

EDIT: Convert String to Code offers a similar approach but it's not fully fleshed out

like image 163
Zhanger Avatar answered Sep 18 '22 03:09

Zhanger