62,621
社区成员
发帖
与我相关
我的任务
分享
package com.j2se.xiaofu;
import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.net.URLClassLoader;
import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import javax.tools.JavaCompiler.CompilationTask;
public class Aotian16 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
doProxy("1+2*3/6");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void doProxy(String str) throws Exception{
String rt = "\r\n";
String src =
"package com.j2se.xiaofu;" + rt+
"public class eval1{" +rt+
" public void doSum(){" +rt+
" System.out.println(" +str+
");" +rt+
" }" +rt+
"}";
String fileName = System.getProperty("user.dir")
+ "/src/com/j2se/xiaofu/eval1.java";
File f = new File(fileName);
FileWriter fw = new FileWriter(f);
fw.write(src);
fw.flush();
fw.close();
//compile
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileMgr = compiler.getStandardFileManager(null, null, null);
Iterable units = fileMgr.getJavaFileObjects(fileName);
CompilationTask t = compiler.getTask(null, fileMgr, null, null, null, units);
t.call();
fileMgr.close();
//load into memory and create an instance
URL[] urls = new URL[] {new URL("file:/" + System.getProperty("user.dir") +"/src")};
URLClassLoader ul = new URLClassLoader(urls);
Class c = ul.loadClass("com.j2se.xiaofu.eval1");
Constructor ctr = c.getConstructor();
eval1 e = (eval1)ctr.newInstance();
e.doSum();
}
}
运行结果:2