Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

Can I call Java from Node.js via JNI and how?

can I call Java from Node.js via JNI? Are there any examples?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should try the node-java npm module which is a well-written wrapper over JNI.

node-jave doesn't appear to (yet) have broad adoption, but playing with it, I've been impressed with how straightforward and robust it has been.

It's as simple as:

var list = java.newInstanceSync("java.util.ArrayList");
list.addSync("item1");
list.addSync("item2");
console.log(list.getSync(1)); // prints "item2"

You can do just about anything with your embedded JVM - create objects, call methods, access fields, etc.

There is a slight impedance mismatch between Node and Java, so if you are going to interact with something complicated, I'd recommend writing most of your interactions in Java and exposing a simpler interface across the Node/Java barrier. It just makes for easier debugging that way.

--- Dave

p.s., RealWorldUseCase(tm): I worked at a place that had a pretty complex (and spaghetti-coded) protocol between multiple browser clients and a Java-based service. I wrote a pretty sweet test-harness which used jsdom to host N simulated browsers and used node-java as a wrapper around the Java service code. It was trivial to shim out the transport interfaces, both in JS for the clients, and in Java for the service, so whenever any of these things sends a message, I capture that and stick it in a queue for probabilistic delivery to the intended target (ie, I virtualized the network). In this way, I could run a full-on simulation of multiple clients interacting with and through a Java service, and run the whole thing inside a single process without any wire communication. And then I could do fun stuff like deliberately reorder message deliveries to make sure the code was resilient to timing bugs. And when a bug was discovered, I had the message orderings logged and could reproduce them to repro the bug. Oh, and the whole thing set up and ran a pretty complex scenario with a few thousand lines of logging and finished in under 1 second per run. 2-weeks well spent. Fun stuff.

RealWorld Use Case #2: selenium-inproc - a module that wraps the SeleniumRC JAR file providing a node interface to browser automation testing w/ Selenium without having to run yet another localhost service.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...