Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to call Java code from Python?

Tags:

java

python

I have a Java class library (3rd party, proprietary) and I want my python script to call its functions. I already have java code that uses this library. What is the best way to achieve this?

like image 404
Martha Yi Avatar asked Dec 06 '09 12:12

Martha Yi


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 you call a Java program?

To call a method in Java, simply write the method's name followed by two parentheses () and a semicolon(;).


2 Answers

Can you run your current Python scripts under Jython ? If so, that's probably the best way, since the Java library can be exposed directly into Jython as scriptable objects.

Failing that, there are a number of solutions listed here.

like image 190
Brian Agnew Avatar answered Oct 10 '22 02:10

Brian Agnew


The other answer is JPype, which allows CPython to talk to Java. It's useful if you can't switch to Jython.

like image 21
Jason Orendorff Avatar answered Oct 10 '22 02:10

Jason Orendorff