JS: fix unwrapping JS objects implemented in Java

This commit is contained in:
Alexey Andreev 2023-11-26 21:57:19 +01:00
parent 1c292f3fbe
commit 9757213379
2 changed files with 52 additions and 2 deletions

View File

@ -165,14 +165,14 @@ public final class JSWrapper {
if (o == null) { if (o == null) {
return null; return null;
} }
return ((JSWrapper) o).js; return o instanceof JSWrapper ? ((JSWrapper) o).js : directJavaToJs(o);
} }
public static JSObject maybeUnwrap(Object o) { public static JSObject maybeUnwrap(Object o) {
if (o == null) { if (o == null) {
return null; return null;
} }
return isJava(o) ? unwrap(o) : directJavaToJs(o); return o instanceof JSWrapper ? unwrap(o) : directJavaToJs(o);
} }
public static JSObject javaToJs(Object o) { public static JSObject javaToJs(Object o) {

View File

@ -292,6 +292,25 @@ public class JSWrapperTest {
assertEquals(JSNumber.valueOf(23), getProperty(o, "foo")); assertEquals(JSNumber.valueOf(23), getProperty(o, "foo"));
} }
@Test
public void createArray() {
var array = new J[] {
new JImpl(23),
new JImpl(42)
};
assertEquals(23, array[0].foo());
assertEquals(42, callFoo(array[1]));
assertEquals("23,42", concatFoo(array));
}
@Test
public void createArrayAndReturnToJS() {
assertEquals("23,42", concatFoo(() -> new J[] {
new JImpl(23),
new JImpl(42)
}));
}
private void callSetProperty(Object instance, Object o) { private void callSetProperty(Object instance, Object o) {
setProperty(instance, "foo", o); setProperty(instance, "foo", o);
} }
@ -341,4 +360,35 @@ public class JSWrapperTest {
interface ReturningObject extends JSObject { interface ReturningObject extends JSObject {
Object get(); Object get();
} }
@JSBody(params = "o", script = "return o.foo();")
private static native int callFoo(JSObject o);
@JSBody(params = "array", script = "return array[0].foo() + ',' + array[1].foo(); ")
private static native String concatFoo(J[] array);
@JSBody(params = "supplier", script = "let array = supplier.get(); "
+ "return array[0].foo() + ',' + array[1].foo();")
private static native String concatFoo(JArraySupplier supplier);
interface J extends JSObject {
int foo();
}
class JImpl implements J {
private int value;
JImpl(int value) {
this.value = value;
}
@Override
public int foo() {
return value;
}
}
interface JArraySupplier extends JSObject {
J[] get();
}
} }