Calling Java code from a JavaScript adapter

Follow these instructions to instantiate Java™ objects and call their methods from JavaScript code in your adapter.

Before you begin

Attention: The name of any Java package to which you refer from within an adapter must start with the domains com, org, or net.

Procedure

  1. Instantiate a Java object by using the new keyword and apply the method on the newly instantiated object.
  2. Optional: Assign a JavaScript variable to be used as a reference to the newly instantiated object. For example:
    var x = new MyJavaClass();
    var y = x.myMethod(1, "a");
  3. Add the Java classes in either of the following ways:

Example

The following snippets demonstrate how to invoke custom Java classes from the JavaScript code in your adapter. Assume you are adding a class Calculator to your Java class and that it contains a static method addTwoIntegers and an instance method subtractTwoIntegers:
public class Calculator {
    // Add two integers 
    public static int addTwoIntegers (int first, int second){
        return first+second ; 
    } 

    // Subtract two integers 
    public int subtractTwoIntegers (int first, int second){
        return first-second ; 
    } 
}
Invoke the static Java method and use the full class name to reference it directly
function addTwoIntegers (a, b){ 
    return {
        result: com.sample.customcode.Calculator.addTwoIntegers (a, b) 
        }; 
}
Use the instance method: create a class instance and invoke the instance method from it
function subtractTwoIntegers (a, b){
    var calcInstance = new com.sample.customcode.Calculator(); 
    return { 
        result: calcInstance.subtractTwoIntegers (a, b) 
    }; 
}