NativeScript+TypeScript实现Java接口时JNI参数错误问题
Looks like you hit a common pitfall with NativeScript's Java interface integration! The JNI error occurs because your Cat class wasn't being properly generated as a Java proxy that implements com.test.Animal—the root issue is how you're using the @Interfaces decorator.
What Went Wrong
NativeScript's @Interfaces decorator expects an array of Java interfaces, even when you only implement one. You passed com.test.Animal directly instead of wrapping it in an array, so the decorator failed to register the interface correctly. That's why the generated proxy class ended up as com.tns.gen.java.lang.Object_cat_6_28_Cat (a plain Object subclass) instead of a class that implements Animal, causing the JNI type mismatch.
Corrected Code
Here's the fixed version of your Cat class:
import { Interfaces } from "@nativescript/core"; // Wrap the interface in an array (required even for single interfaces) @Interfaces([com.test.Animal]) export class Cat { constructor() { return global.__native(this); } public eat(): void { console.log("cat is eating"); } }
Additional Checks to Ensure Success
- Verify Native Plugin Integration: Make sure the aar/jar containing
com.test.Animalandcom.test.Boxis placed inApp_Resources/Android/libsand properly referenced in your project configuration. - Type Declarations: If using TypeScript, ensure the
com.testpackage types are available (viatns-platform-declarationsor a customreferences.d.tsfile) to catch type issues at compile time. - Method Signature Match: Your
eat()method already matches the Java interface exactly (no parameters, void return), so this part is correct.
Test the Fixed Code
Your existing calling logic doesn't need changes:
import { Cat } from "./cat" let box = new com.test.Box(); box.setAnimal(new Cat()); box.startEat();
With this fix, NativeScript will generate a proxy class that properly implements com.test.Animal, the JNI type check will pass, and you'll see "cat is eating" logged as expected.
内容的提问来源于stack exchange,提问作者Andy Ma

