node-jvm,使用纯node.js实现了JVM,太酷了!
例如,下面是一段生成斐波纳契数列并计算生成时间的Java代码:
public class Main {
public static long fib(int n) {
if (n <= 1) return n;
return fib(n-1) + fib(n-2);
}
public static void main(String[] args) {
if (args.length == 0) {
System.out.print("help: java Main.class {Number}");
return;
}
int N = Integer.parseInt(args[0]);
long start = System.currentTimeMillis();
System.out.format("Fibonacci from 1 to %s:\n", N);
for (int i = 1; i <= N; i++) {
System.out.println(i + ": " + fib(i));
}
long stop = System.currentTimeMillis();
System.out.println("time: " + (stop - start) + "ms");
System.out.println("done.");
}
}
将它保存为Main.jar
,然后加载到node-jvm
中:
var JVM = require("node-jvm");
var jvm = new JVM();
jvm.setLogLevel(7);
var entryPointClassName = jvm.loadJarFile("./Main.jar");
jvm.setEntryPointClassName(entryPointClassName);
jvm.on("exit", function(code) {
process.exit(code);
});
jvm.run([15]);
构建:
cd examples/fibonacci
make
运行:
./fibonacci.js
输出:
Fibonacci from 1 to 15:
1: 1
2: 1
3: 2
4: 3
5: 5
6: 8
7: 13
8: 21
9: 34
10: 55
11: 89
12: 144
13: 233
14: 377
15: 610
time: 106ms
done.
node-jvm在MIT许可下发布,项目主页在此。
编撰 SegmentFault
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。