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.
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.
The seamless interaction between Python and Java allows developers to freely mix the two languages both during development and in shipping products.
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.
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.)"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With