0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

NativeScriptで、未定義の外部Javaクラスをextendsして新しいクラスを作る

0
Posted at

NativeScriptでAndroidのSDKに含まれていない外部Javaクラスを使う方法は前に述べましたが、今回は、外部のJavaクラスをextendsして新しいクラスを作る方法になります。

たとえば、com.socdm.d.adgeneration.ADGListener というパッケージのクラスを基底クラスとして AdListener という新しいクラスを作るときのことを考えてみましょう。

まず以下のような記述をおこないます。

declare let com:any;

comパッケージをany型で宣言しています。これは、TypeScriptでcom.socdm.d.adgeneration.ADGListenerをコンパイルエラーにさせないために必要です。

次に以下のように書きます。

class AdListener extends com.socdm.d.adgeneration.ADGListener {

			onReceiveAd() {
				console.log("onReceiveAd");
			}

			constructor(){
				super(); // ここでエラー!
				return global.__native(this);
			}
}

通常はこれで完成。なのですが...super(); の行で、下記のようなエラーが発生します。

 TS2346: Call target does not contain any signatures

これは、super() で呼ぶ先の親のコンストラクタに関する情報が全く無いから、呼べないよ!ということになります。any型なんだから、とにかく呼んでくれよ!と思うわけですが、どうやらコンストラクタについては引数や戻り値の最低限の定義が必要なようです。

そこで以下のようにextendsのあとを書き換えます。

class AdListener extends (com.socdm.d.adgeneration.ADGListener as { new(): any; }) {

			onReceiveAd() {
				console.log("onReceiveAd");
			}

			constructor(){
				super();
				return global.__native(this);
			}
}

{ new(): any; } の部分で コンストラクタの形を定義しています。引数なしで、戻り値はany型である、という定義をしていますね。これでコンパイルが通るようになります。

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?