最近根据公司的业务需要通过前端页面传过来字符串的代码,并且通过动态编译然后执行,支持的类型为 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(); } }


发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/215300.html原文链接:https://javaforall.net
