最近根据公司的业务需要通过前端页面传过来字符串的代码,并且通过动态编译然后执行,支持的类型为 JS、Java字符串、class文件 的方式,由于实现的方式都各不相同,所以进行统一封装一下
1. 代码结构
2. 实现结果测试
2.1 JS代码
@Test
public void test_Js_compile() throws ScriptException, NoSuchMethodException, InterruptedException {
CompletableFuture.runAsync(() -> {
String str = "function bbb() { print(a); return a}; bbb()";
Map<String, Object> map = new HashMap<>();
map.put("a", "hello world");
DynamicCompileWrapper<?> scriptEngine = DynamicCompileFactory.getScriptEngine(DynamicCompileType.JS);
try {
scriptEngine.execFunction(str, map);
} catch (DynamicCompileException e) {
e.printStackTrace();
}
});
CompletableFuture.runAsync(() -> {
String str = "function bbb() { print(a); return a}; ";
Map<String, Object> map = new HashMap<>();
map.put("a", "hello world2");
DynamicCompileWrapper<?> scriptEngine = DynamicCompileFactory.getScriptEngine(DynamicCompileType.JS);
try {
scriptEngine.execFunctionForMethodName(str, "bbb", map);
} catch (Exception e) {
e.printStackTrace();
}
});
Thread.currentThread().join();
}
2.2 Java代码
@Test
public void test_java_compile() throws ClassNotFoundException, InvocationTargetException, IllegalAccessException, NoSuchMethodException {
String code = "public class HelloWorld {\n" +
" public void add(String a) {System.out.println(a);}\n" +
" \n" +
"}";
DynamicCompileWrapper<JavaCompile> scriptEngine = (DynamicCompileWrapper<JavaCompile>) DynamicCompileFactory.getScriptEngine(DynamicCompileType.JAVA);
JavaCompile engine = scriptEngine.getScriptEngine(code);
engine.runMethod("add", "hello");
}
2.3 Java文件
@Test
public void test_java_file() {
File file = new File("E:\\my-study-project\\practice\\src\\main\\java\\com\\zhj\\demo\\tls\\Tlsdemo.java");
JavaCompile javaCompile = null;
try {
FileInputStream inputStream = new FileInputStream(file);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int tempChar;
while ((tempChar = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, tempChar);
}
javaCompile = createInstance().getScriptEngine(new String(outputStream.toByteArray(), StandardCharsets.UTF_8));
javaCompile.runMainMethod(new String[]{
});
} catch (Exception e) {
e.printStackTrace();
}
}
今天的文章Java封装动态编译分享到此就结束了,感谢您的阅读。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/7144.html