梗概

在同一个进程中调用

  • 在Java中使用NashornRhino或其他JavaScript引擎来执行JavaScript代码,并在Java代码中调用JavaScript函数。
  • 使用J2V8封装后的V8引擎来执行JavaScript代码

另起一个进程进行调用

实例

在拥有nodejs的系统上

import java.io.*;
 
public class Main {
    public static void main(String[] args) {
        try {
            Process process = Runtime.getRuntime().exec("node -e \"console.log('Hello World')\"");
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

输出:Hello World