JavaScript アダプターでの Java の使用

improve this page | report issue

概説

必要な機能を実装するのに JavaScript では不十分な場合や既存の Java クラスがある場合には、JavaScript アダプターの拡張として Java コードを使用することができます。

前提条件: 最初に必ず、JavaScript アダプターチュートリアルをお読みください。

カスタム Java クラスの追加

UsingJavainJS

既存の Java ライブラリーを使用するには、JAR ファイルを依存関係としてプロジェクトに追加します。 依存関係の追加方法について詳しくは、Java アダプターおよび JavaScript アダプターの作成チュートリアルの『依存関係』セクションを参照してください。

カスタム Java コードをプロジェクトに追加するには、アダプター・プロジェクトの src/main フォルダーに java という名前のフォルダーを追加して、そこにパッケージを置きます。 このチュートリアルのサンプルでは、com.sample.customcode パッケージと Java クラス・ファイル名 Calculator.java を使用します。

重要: パッケージ名の先頭は comorg、または net でなければなりません。

Java クラスにメソッドを追加します。
静的メソッドの例 (新規インスタンスを必要としません) とインスタンス・メソッドの例を以下に示します。

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;
  }
}

アダプターからのカスタム Java クラスの呼び出し

カスタム Java コードを作成して必要な JAR ファイルを追加すると、そのファイルを JavaScript コードから呼び出すことができます。

  • 静的 Java メソッドを次のようにして呼び出し、完全クラス名を使用して直接参照します。
function addTwoIntegers(a,b){
    return {
        result: com.sample.customcode.Calculator.addTwoIntegers(a,b)
    };
}
  • インスタンス・メソッドを使用するには、クラス・インスタンスを作成して、そのインスタンスからインスタンス・メソッドを呼び出します。
function subtractTwoIntegers(a,b){
    var calcInstance = new com.sample.customcode.Calculator();   
    return {
        result : calcInstance.subtractTwoIntegers(a,b)
    };
}

サンプル・アダプター

ここをクリック して Maven プロジェクトをダウンロードします。

使用例

テスト時には、アダプターは、例えば [1,2] のような、加算または減算する数値を持つ配列を予期しています。

Inclusive terminology note: The Mobile First Platform team is making changes to support the IBM® initiative to replace racially biased and other discriminatory language in our code and content with more inclusive language. While IBM values the use of inclusive language, terms that are outside of IBM's direct influence are sometimes required for the sake of maintaining user understanding. As other industry leaders join IBM in embracing the use of inclusive language, IBM will continue to update the documentation to reflect those changes.
Last modified on March 15, 2018