Skip to content

Commit f3ca862

Browse files
committed
unix/modjni: Implement len() for objects with java.util.List interface.
1 parent 7702028 commit f3ca862

1 file changed

Lines changed: 21 additions & 0 deletions

File tree

unix/modjni.c

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
#include <dlfcn.h>
3131

3232
#include "py/nlr.h"
33+
#include "py/runtime0.h"
3334
#include "py/runtime.h"
3435
#include "py/binary.h"
3536

@@ -51,6 +52,7 @@ static jmethodID Method_toString_mid;
5152
static jclass List_class;
5253
static jmethodID List_get_mid;
5354
static jmethodID List_set_mid;
55+
static jmethodID List_size_mid;
5456

5557
STATIC const mp_obj_type_t jobject_type;
5658
STATIC const mp_obj_type_t jmethod_type;
@@ -207,10 +209,27 @@ STATIC mp_obj_t jobject_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value)
207209
return MP_OBJ_NULL;
208210
}
209211

212+
STATIC mp_obj_t jobject_unary_op(mp_uint_t op, mp_obj_t self_in) {
213+
mp_obj_jobject_t *self = self_in;
214+
switch (op) {
215+
case MP_UNARY_OP_BOOL:
216+
case MP_UNARY_OP_LEN: {
217+
jint len = JJ(CallIntMethod, self->obj, List_size_mid);
218+
if (op == MP_UNARY_OP_BOOL) {
219+
return MP_BOOL(len != 0);
220+
}
221+
return MP_OBJ_NEW_SMALL_INT(len);
222+
}
223+
default:
224+
return MP_OBJ_NULL; // op not supported
225+
}
226+
}
227+
210228
STATIC const mp_obj_type_t jobject_type = {
211229
{ &mp_type_type },
212230
.name = MP_QSTR_jobject,
213231
.print = jobject_print,
232+
.unary_op = jobject_unary_op,
214233
.attr = jobject_attr,
215234
.subscr = jobject_subscr,
216235
// .locals_dict = (mp_obj_t)&jobject_locals_dict,
@@ -471,6 +490,8 @@ STATIC void create_jvm() {
471490
"(I)Ljava/lang/Object;");
472491
List_set_mid = JJ(GetMethodID, List_class, "set",
473492
"(ILjava/lang/Object;)Ljava/lang/Object;");
493+
List_size_mid = JJ(GetMethodID, List_class, "size",
494+
"()I");
474495
}
475496

476497
STATIC mp_obj_t mod_jni_cls(mp_obj_t cls_name_in) {

0 commit comments

Comments
 (0)