如何从java代码本身运行编译代码(.class
)java?从java代码运行.class文件
我正在做一种提供服务,如在服务器端编译和运行java代码并将输出提供给最终用户。
任何人都可以提出一个方法来实现这个目标吗?
import java.io.*;
public class demo {
public static void main(String args[]) throws IOException, InterruptedException {
int result;
try {
System.out.println("command output:");
Process proc = Runtime.getRuntime().exec("java -cp . demoh");
InputStream in = proc.getInputStream();
result = proc.waitFor();
BufferedInputStream buffer = new BufferedInputStream(proc.getInputStream());
BufferedReader commandOutput = new BufferedReader(new InputStreamReader(buffer));
System.out.print(commandOutput);
String line = null;
try {
while ((line = commandOutput.readLine()) != null) {
System.out.print(line);
System.out.println("command output: " + line);
}//end while
commandOutput.close();
} catch (IOException e) {
//log and/or handle it
}
} catch (IOException e) {
System.err.println("IOException raised: " + e.getMessage());
}
}
}
*“我在做类似的服务,比如在服务器端编译和运行java代码,并给出最终用户?”*不妨安装tomcat并让用户访问上传servlet,这将是关于同样的安全噩梦。事实上,想想看,如果你继续这样做,你不妨同时把钥匙给你的房子。 ;) – 2012-04-20 16:12:36
@AndrewThompson可以在沙箱中运行它 – siamii 2012-04-20 16:23:11
@ bizso09确实如此,但那意味着许多有趣的代码类型将无法运行。即使这样,你也必须考虑编程错误('OutOfMemroyError','StackOverflowError',无限循环..)。事实上,一旦我有一个在线编译器(无法运行代码)。一位对我正在使用的编译器有深入了解的人联系了并警告我完全基于***编译***代码的DOS攻击。至少(至少很久以前)的代码可能会使编译器占用30分钟或更长的时间! – 2012-04-20 16:27:50