动态编译
/**
* 动态编译
* @author L J
*/
@SuppressWarnings("all")
public class TestCompile {
public static void main(String[] args) {
String str = "public class Compile {public static void main(String[] args) {System.out.println(\"hello world!\");}}";
try {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("F:/DB/Compile.java")));
writer.write(str);
writer.flush();
writer.close();
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int result = compiler.run(null, null, null, "F:/DB/Compile.java");
System.out.println(result == 0 ? "编译成功" : "编译失败");
URL[] urls = new URL[]{new URL("file:/" + "F:/DB/")};
URLClassLoader loader = new URLClassLoader(urls);
Class c = loader.loadClass("Compile");
Method m = c.getMethod("main", String[].class);
m.invoke(null, (Object)new String[]{"aa", "bb"});
} catch (Exception e) {
e.printStackTrace();
}
}
}
用脚本引擎执行javascript代码
/**
* 测试脚本引擎执行javascript代码
* @author L J
*/
@SuppressWarnings("all")
public class JavaScriptEngine {
public static void main(String[] args) throws Exception {
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine engine = sem.getEngineByName("javascript");
engine.put("msg", "that's why you go away!");
String str = "var user = {name:'小明', age:18, schools:['清华大学', '北京大学']};";
str += "println(user.name)";
engine.eval(str);
engine.eval("msg = 'baby!'");
System.out.println(engine.get("msg"));
engine.eval("function add(a, b) {var sum = a + b; return sum}");
Invocable jsInvoke = (Invocable) engine;
Object result = jsInvoke.invokeFunction("add", new Object[]{12, 23});
System.out.println(result);
String jsCode = "importPackage(java.util);" +
"var list = Arrays.asList([\"清华大学\", \"北京大学\", \"浙江大学\"]);";
engine.eval(jsCode);
List<String> list = (List<String>) engine.get("list");
for(String temp : list) {
System.out.println(temp);
}
URL url = JavaScriptEngine.class.getClassLoader().getResource("test.js");
FileReader fr = new FileReader(url.getPath());
engine.eval(fr);
fr.close();
}
}