Using Java in JavaScript adapters
improve this page | report issueOverview
To learn more about adapters in general, start with the Adapters Overview tutorial.
When JavaScript is not sufficient to implement required functionality, or if a Java class already exists, you can use Java code as an extension for the JavaScript adapter.
This tutorial covers the following topics:
Adding custom Java classes
- To use an existing Java library, add the JAR file to the
server\lib
folder of your MobileFirst project.After the adapter is built and deployed, this JAR file is automatically deployed to MobileFirst Server.
- To add custom Java code to your project, right-click the
server/java
folder in your MobileFirst project and add a Java class file. Name itCalculator.java
.Important: The package name must start with either
com
,org
, ornet
. - Add this file to a package. This sample uses the
com.sample.customcode
package.
This package name can be interpreted as folders:java\com\sample\customcode
- Add methods to your
Calculator.java
class.
Here is an example of a static method (does not require a new instance) and of an instance method.package com.sample.customcode; 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; } }
- If your Java code has additional dependencies, put the required JAR files in the
server\lib
folder of your MobileFirst project.
Invoking custom Java classes from the adapter
After your custom Java code is created and any required JAR files are added, you can reference it from your MobileFirst adapter JavaScript as if it were written in Java.
- Invoke the static Java method as shown, and use the full class name to reference it directly.
function addTwoIntegers(a,b){ return { result: com.sample.customcode.Calculator.addTwoIntegers(a,b) }; }
- To 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) }; }
Sample application
Click to download the MobileFirst project.
▲