Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call non-native Java code from Python

Tags:

java

python

cgi

I want to be able to call certain methods and such that are contained in a Java jar that is already running (It is guaranteed that it will be running). I have found things like Jython, but those only seem to be able to access Java's native classes and such.

like image 548
Greg Avatar asked Jun 16 '12 16:06

Greg


People also ask

Can we call Java method from Python?

Py4J enables Python programs running in a Python interpreter to dynamically access Java objects in a Java Virtual Machine. Methods are called as if the Java objects resided in the Python interpreter and Java collections can be accessed through standard Python collection methods.

Can Python interact with Java?

The seamless interaction between Python and Java allows developers to freely mix the two languages both during development and in shipping products.

How do I import Java into Python?

We can import any java package or class in Jython, just as we do in a Java program. The following example shows how the java. util packages are imported in Python (Jython) script to declare an object of the Date class. Save and run the above code as UtilDate.py from the command line.


1 Answers

Check out this: Calling Java from Python

"You could also use Py4J. There is an example on the frontpage and lots of documentation, but essentially, you just call Java methods from your python code as if they were python methods:

from py4j.java_gateway import JavaGateway

gateway = JavaGateway() # connect to the JVM

java_object = gateway.jvm.mypackage.MyClass() # invoke constructor

other_object = java_object.doThat()

other_object.doThis(1,'abc')

gateway.jvm.java.lang.System.out.println('Hello World!') # call a static method

As opposed to Jython, one part of Py4J runs in the Python VM so it is always "up to date" with the latest version of Python and you can use libraries that do not run well on Jython (e.g., lxml). The other part runs in the Java VM you want to call.

The communication is done through sockets instead of JNI and Py4J has its own protocol (to optimize certain cases, to manage memory, etc.)"

like image 98
tabchas Avatar answered Oct 05 '22 06:10

tabchas