@@ -319,7 +319,10 @@ class Main {
319
319
}
320
320
` ` `
321
321
#### Interop Types
322
- The ` register_interop_type` API allows the usage of python classes for foreign objects:
322
+ The ` register_interop_type` API allows the usage of python classes for foreign objects.
323
+ The type of such a foreign object will no longer be ` foreign` .
324
+ Instead, it will be a generated class with the registered python classes and ` foreign` and as super classes.
325
+ This allows mapping foreign methods and attributes to Python's magic method or more idiomatic Python code.
323
326
324
327
` ` ` java
325
328
package org .example ;
@@ -366,6 +369,7 @@ import java
366
369
from polyglot import register_interop_type
367
370
368
371
print (my_java_object .getX ()) # 42
372
+ print (type (my_java_object)) # < class ' foreign' >
369
373
370
374
class MyPythonClass :
371
375
def get_tuple (self ):
@@ -376,13 +380,23 @@ foreign_class = java.type("org.example.MyJavaClass")
376
380
register_interop_type (foreign_class, MyPythonClass)
377
381
378
382
print (my_java_object .get_tuple ()) # (42 , 17 )
383
+ print (type (my_java_object)) # < class ' polyglot.Java_org.example.MyJavaClass_generated' >
384
+ print (type (my_java_object).mro ()) # [generated_class, MyPythonClass, foreign, object]
379
385
380
386
class MyPythonClassTwo :
381
- def __str__ (self ):
382
- return f" MyJavaInstance(x={self.getX()}, y={self.getY()}"
387
+ def get_tuple (self ):
388
+ return (self .getY (), self .getX ())
389
+ def __str__ (self ):
390
+ return f" MyJavaInstance(x={self.getX()}, y={self.getY()}"
391
+
392
+ # If ' allow_method_overwrites=False' or not given, this would lead to an error due to the method conflict of ' get_tuple'
393
+ register_interop_type (foreign_class, MyPythonClassTwo, allow_method_overwrites= True)
383
394
384
- register_interop_type (foreign_class, MyPythonClassTwo)
395
+ # A newly registered class will be before already registered classes in the mro.
396
+ # It allows overwriting methods from already registered classes with the flag ' allow_method_overwrites=True'
397
+ print (type (my_java_object).mro ()) # [generated_class, MyPythonClassTwo, MyPythonClass, foreign, object]
385
398
399
+ print (my_java_object .get_tuple ()) # (17 , 42 )
386
400
print (my_java_object) # MyJavaInstance (x= 42 , y= 17 )
387
401
` ` `
388
402
0 commit comments