Python as "host" language in graalvm

Plaiska :

I'm trying to access Java objects from Python code using graalvm. Can someone point me to sample code? Essentially I want to be able to run graalpython --polyglot --jvm myscript.py where myscript.py is able to instantiate a Java object

I've gone through the graalvm documentation and the only example I've found instantiates Java arrays from Python code (See below) I've also gone through the polyglot examples in this link https://www.graalvm.org/docs/reference-manual/embed/#access-java-from-guest-languages and that essentially runs Java polyglot API which runs python code that accesses the java object , but that's not what I want.

The code example below is from this link which also mentions "and accessing other classes than Java arrays, it is required to recompile the image and provide a reflection configuration file" but I don't quite understand how I can do this.

import java

array = java.type("int[]")(4)
array[2] = 42
print("Printing Java Array" , array[2])

I tried modifying the code above to this:

import java
import polyglot

array = java.type("int[]")(4)
array[2] = 42
print("Printing Java Array" , array[2])
# Just to see if I can access Java , example copied from Javascript -> Java 
re = polyglot.eval(string="RegExp()", language="java") 

And I got the following o/p:

Printing Java Array 42
Traceback (most recent call last):
File "polyglot.py", line 8, in <module 'polyglot.py'>
re = polyglot.eval(string="RegExp()", language="java")
NotImplementedError: No language for id java found. Supported   languages are: [internal/nfi-native, nfi, regex, js, llvm, python, ruby]
timfelgentreff :

You cannot evaluate Java code from a String - the Java language is special in that it is the host language - you can only access what is available (as bytecode) on the classpath. To access Java, you have to write Python code to do it, not Java code, e.g.:

import java
regexpClass = java.type("sun.misc.Regexp")
javaRegexp = regexpClass("hello")

The objects behave reasonably Python-ish, i.e., instantiation is the same as invocation, dir(javaRegexp) will give you the available Java methods and so on.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=145937&siteId=1