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 +

  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


      
  1. public class HelloWorld {

  2.  public static void main(String[] args) {

  3.      System.out.println("Hello World!");

  4.  }

  5. }

Copy the code

Output: Hello World!

  • Node.js


      
  1. const java = require('java')

  2. const javaLangSystem = java.import('java.lang.System')

  3. javaLangSystem.out.printlnSync('Hello World! ')

Copy the code

Output: Hello World!

Operating a Java Map

Java HashMap operation


      
  1. import java.util.HashMap;

  2. import java.util.Map;

  3. public class HashMapDemo {

  4.  public static void main(String[] args) {

  5.    Map<String. Object> map = new HashMap< > ();

  6.    map.put("name". "SunilWang");

  7.    map.put("age". 20);

  8.    String name = (String) map.get("name");

  9.    int age = (int) map.get("age");

  10.    System.out.printf(Name: "" % s". name);

  11.    System.out.println("");

  12.    System.out.printf("Age: % d". age);

  13.  }

  14. }

Copy the code

Output: name: SunilWang age: 20

Node.js calls the Java HashMap synchronously


      
  1. const java = require('java')

  2. const HashMap = java.import('java.util.HashMap')

  3. // Synchronize the operation

  4. let hashMap = new HashMap(a)

  5. hashMap.putSync('name'. 'SunilWang')

  6. hashMap.putSync('age'. 20)

  7. let name = hashMap.getSync('name')

  8. let age = hashMap.getSync('age')

  9. console.log('name'. name)

  10. console.log('age'. age)

Copy the code

Output: name: SunilWang age: 20

Node.js callback calls the Java HashMap


      
  1. const java = require('java')

  2. const HashMap = java.import('java.util.HashMap')

  3. / / callback operation

  4. let hashMap = new HashMap(a)

  5. hashMap.put('name'. 'SunilWang'. (error. info) = > {

  6.  if (error) console.log('put name Error: '. error)

  7.  hashMap.get('name'. (error. name) = > {

  8.    if (error) console.log('get name Error: '. error)

  9.    console.log('% s' callback name.. name)

  10.  })

  11. })

Copy the code

Output: callback name: SunilWang

Node.js Promise calls the Java HashMap


      
  1. const co = require('co')

  2. const java = require('java')

  3. // The current configuration must be declared at the top

  4. java.asyncOptions = {

  5.  syncSuffix: 'Sync'. // Synchronization method name suffix

  6.  asyncSuffix: ' '. // Asynchronous method name suffix

  7.  promiseSuffix: 'Promise'. // Promise method name suffix

  8.  promisify: require('bluebird').promisify // The module that depends on Promise

  9. }

  10. / / = = = = = = = = = = = = = =

  11. const HashMap = java.import('java.util.HashMap')

  12. / / Promise

  13. co(function * (a) {

  14.  let hashMap = new HashMap(a)

  15.  yield hashMap.putPromise('name'. 'SunilWang')

  16.  yield hashMap.putPromise('age'. '20')

  17.  let name = yield hashMap.getPromise('name')

  18.  let age = yield hashMap.getPromise('age')

  19.  console.log('name'. name)

  20.  console.log('age'. age)

  21. })

Copy the code

There are two ways to create a Java instance

  • Java


      
  1. import java.util.ArrayList;

  2. import java.util.List;

  3. public class ArrayListDemo {

  4.  public static void main(String[] args) {

  5.    List<String> list1 = new ArrayList< > ();

  6.    List<String> list2 = new ArrayList< > ();

  7.    list1.add("item1");

  8.    list2.add("item1");

  9.    System.out.printf("size: %d". list1.size()); / / 2

  10.    System.out.println("");

  11.    // list1 equals list2: true

  12.    System.out.printf("list1 equals list2: %s". list1.equals(list2));

  13.  }

  14. }

Copy the code

newInstanceSync


      
  1. const java = require('java')

  2. let list1 = java.newInstanceSync('java.util.ArrayList')

  3. console.log(list1.sizeSync()) / / 0

  4. list1.addSync('item1')

  5. console.log(list1.sizeSync()) / / 1

Copy the code

import & new


      
  1. let ArrayList = java.import('java.util.ArrayList')

  2. let list2 = new ArrayList(a)

  3. list2.addSync('item1')

  4. let equalValue = list2.equalsSync(list1)

  5. console.log(equalValue)// true

Copy the code

Other operating

Fast new data group

  • Java


      
  1. public class CharArrayDemo {

  2.  public static void main(String[] args) {

  3.    char [] charArray = "hello world\n".toCharArray(a);

  4.    // charArray length: 12

  5.    System.out.printf("charArray length: %d". charArray.length);

  6.  }

  7. }

Copy the code
  • Node.js


      
  1. let charArray = java.newArray('char'. 'hello world\n'.split(' '))

  2. // [ 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '\n' ]

  3. console.log(charArray.length) / / 12

Copy the code

Fast New Long object

  • Java


      
  1. public class LongDemo {

  2.  public static void main(String[] args) {

  3.    Long num = new Long("5");

  4.    System.out.println(num);

  5.    System.out.println(num.longValue());

  6.  }

  7. }

Copy the code
  • Node.js


      
  1. let javaLong = java.newInstanceSync('java.lang.Long'. 5)

  2. // Possibly truncated long value: 5

  3. console.log('Possibly truncated long value: %d'. javaLong)

  4. // Original long value (as a string): 5

  5. console.log('Original long value (as a string): %s'. javaLong.longValue)

Copy the code

Node.js calls its own compiled classes

  • Java


      
  1. package com.nearinfinity.nodeJava;

  2. public class MyClass {

  3.  public static int addNumbers(int a. int b) {

  4.    return a + b;

  5.  }

  6. }

Copy the code
  • Node.js


      
  1. const java = require('java')

  2. java.classpath.push('./src')

  3. let MyClass = java.import('com.nearinfinity.nodeJava.MyClass')

  4. let result = MyClass.addNumbersSync(1. 2)

  5. console.log(result)

  6. let javaInteger = java.newInstanceSync('java.lang.Integer'. 2)

  7. // Quickly call a method in a Java static class

  8. result = java.callStaticMethodSync('com.nearinfinity.nodeJava.MyClass'. 'addNumbers'. javaInteger. 3)

  9. 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