VUI LÒNG KHÔNG thực sự sử dụng NÀY
Tôi đã theo giả định bạn muốn đánh giá một chuỗi như mã Java, không phải một số động cơ kịch bản như Javascript, vì vậy tôi tạo này trên một ý thích sau khi đọc this, sử dụng nhãn API trình biên dịch được đề cập. Nó có thể là thực hành rất xấu nhưng nó (phần nào) hoạt động như bạn muốn. Tôi nghi ngờ nó sẽ được sử dụng nhiều trong gỡ lỗi vì nó chạy mã trong bối cảnh của một lớp mới. Sử dụng mẫu được bao gồm ở dưới cùng.
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
Với SimpleJavaFileObject bạn thực sự có thể tránh sử dụng một tập tin, như thể hiện here, nhưng cú pháp có vẻ hơi rườm rà vì vậy tôi chỉ lựa chọn một tập tin trong thư mục làm việc hiện hành.
EDIT: Convert String to Code cung cấp một cách tiếp cận tương tự nhưng nó không đầy đủ fleshed ra
câu hỏi thực sự là: ** ** tại sao bạn muốn làm điều này ... – Dariusz
Chúng ta hãy giả định cho một phân chia thứ hai này có thể ... nhưng chỉ nghĩ Java sẽ biên dịch mã thời gian chạy của bạn như thế nào? – AurA
Những gì bạn cần có thể là [trình thông dịch Java] (http://stackoverflow.com/questions/3504396/java-interpreter). – LaurentG