Over the years, JavaScript has gone from being “the world’s most misunderstood language” to “the world’s most popular language” thanks to the rise of Node.js. And the pace of development, in terms of the evolution of the language itself, the growth of libraries and packages, the improvement of tool support, the emergence of STAR projects and domain solutions, the expansion of platforms, technology stacks, application domains, etc., is unprecedented. With the popularity of Node.js services, a question arises for companies whose back-end services are Java: how does Node.js communicate with Java?
What’s on today?
Instead of architectural design and traditional HTTP, socket, and RPC communication protocols, let’s talk about how to connect to Java apis in Node.js applications — in other words, write Java code directly in Node.js.
node-java
To connect node.js to Java, you need a Node-Java module.
Environment to prepare
Operating system: Supports OSX and Linux
Operating environment (recommended) :
-
Install the module
-
The minimum Nodejs LTS version must be 6.x
-
Java JDK 1.8 +
-
Linux GCC 4.8.1 +
-
$ npm install java
If Liunx does not support c++ 11, you need to manually upgrade GCC to GCC 4.8
If you need to install the old Java SE 6 runtime environment, please download JDK 2015
Call the Java Node. Js
HelloWorld
-
java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
Copy the code
Output: Hello World!
-
Node.js
const java = require('java')
const javaLangSystem = java.import('java.lang.System')
javaLangSystem.out.printlnSync('Hello World! ')
Copy the code
Output: Hello World!
Operating a Java Map
Java HashMap operation
import java.util.HashMap;
import java.util.Map;
public class HashMapDemo {
public static void main(String[] args) {
Map<String. Object> map = new HashMap< > ();
map.put("name". "SunilWang");
map.put("age". 20);
String name = (String) map.get("name");
int age = (int) map.get("age");
System.out.printf(Name: "" % s". name);
System.out.println("");
System.out.printf("Age: % d". age);
}
}
Copy the code
Output: name: SunilWang age: 20
Node.js calls the Java HashMap synchronously
const java = require('java')
const HashMap = java.import('java.util.HashMap')
// Synchronize the operation
let hashMap = new HashMap(a)
hashMap.putSync('name'. 'SunilWang')
hashMap.putSync('age'. 20)
let name = hashMap.getSync('name')
let age = hashMap.getSync('age')
console.log('name'. name)
console.log('age'. age)
Copy the code
Output: name: SunilWang age: 20
Node.js callback calls the Java HashMap
const java = require('java')
const HashMap = java.import('java.util.HashMap')
/ / callback operation
let hashMap = new HashMap(a)
hashMap.put('name'. 'SunilWang'. (error. info) = > {
if (error) console.log('put name Error: '. error)
hashMap.get('name'. (error. name) = > {
if (error) console.log('get name Error: '. error)
console.log('% s' callback name.. name)
})
})
Copy the code
Output: callback name: SunilWang
Node.js Promise calls the Java HashMap
const co = require('co')
const java = require('java')
// The current configuration must be declared at the top
java.asyncOptions = {
syncSuffix: 'Sync'. // Synchronization method name suffix
asyncSuffix: ' '. // Asynchronous method name suffix
promiseSuffix: 'Promise'. // Promise method name suffix
promisify: require('bluebird').promisify // The module that depends on Promise
}
/ / = = = = = = = = = = = = = =
const HashMap = java.import('java.util.HashMap')
/ / Promise
co(function * (a) {
let hashMap = new HashMap(a)
yield hashMap.putPromise('name'. 'SunilWang')
yield hashMap.putPromise('age'. '20')
let name = yield hashMap.getPromise('name')
let age = yield hashMap.getPromise('age')
console.log('name'. name)
console.log('age'. age)
})
Copy the code
There are two ways to create a Java instance
-
Java
import java.util.ArrayList;
import java.util.List;
public class ArrayListDemo {
public static void main(String[] args) {
List<String> list1 = new ArrayList< > ();
List<String> list2 = new ArrayList< > ();
list1.add("item1");
list2.add("item1");
System.out.printf("size: %d". list1.size()); / / 2
System.out.println("");
// list1 equals list2: true
System.out.printf("list1 equals list2: %s". list1.equals(list2));
}
}
Copy the code
newInstanceSync
const java = require('java')
let list1 = java.newInstanceSync('java.util.ArrayList')
console.log(list1.sizeSync()) / / 0
list1.addSync('item1')
console.log(list1.sizeSync()) / / 1
Copy the code
import & new
let ArrayList = java.import('java.util.ArrayList')
let list2 = new ArrayList(a)
list2.addSync('item1')
let equalValue = list2.equalsSync(list1)
console.log(equalValue)// true
Copy the code
Other operating
Fast new data group
-
Java
public class CharArrayDemo {
public static void main(String[] args) {
char [] charArray = "hello world\n".toCharArray(a);
// charArray length: 12
System.out.printf("charArray length: %d". charArray.length);
}
}
Copy the code
-
Node.js
let charArray = java.newArray('char'. 'hello world\n'.split(' '))
// [ 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '\n' ]
console.log(charArray.length) / / 12
Copy the code
Fast New Long object
-
Java
public class LongDemo {
public static void main(String[] args) {
Long num = new Long("5");
System.out.println(num);
System.out.println(num.longValue());
}
}
Copy the code
-
Node.js
let javaLong = java.newInstanceSync('java.lang.Long'. 5)
// Possibly truncated long value: 5
console.log('Possibly truncated long value: %d'. javaLong)
// Original long value (as a string): 5
console.log('Original long value (as a string): %s'. javaLong.longValue)
Copy the code
Node.js calls its own compiled classes
-
Java
package com.nearinfinity.nodeJava;
public class MyClass {
public static int addNumbers(int a. int b) {
return a + b;
}
}
Copy the code
-
Node.js
const java = require('java')
java.classpath.push('./src')
let MyClass = java.import('com.nearinfinity.nodeJava.MyClass')
let result = MyClass.addNumbersSync(1. 2)
console.log(result)
let javaInteger = java.newInstanceSync('java.lang.Integer'. 2)
// Quickly call a method in a Java static class
result = java.callStaticMethodSync('com.nearinfinity.nodeJava.MyClass'. 'addNumbers'. javaInteger. 3)
console.log(result)
Copy the code
conclusion
This is just the tip of the node-Java iceberg. The Node-Java API is rich, such as the JVM, instantiating a class, calling class static methods, quickly instantiating an object, and so on.
The quickest way to learn is to look at the documentation: Node-java.
— — — — — — — — —
Long press the QR code to follow the big Zhuan FE