6

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.

1
  • How do you expect to be able to do this from e.g. Java? Commented Jun 16, 2012 at 16:50

1 Answer 1

3

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.)"

Sign up to request clarification or add additional context in comments.

1 Comment

From the Py4J Website: "Note that the Java program must be started before executing the Python code above. In other words, the Py4J does not start a JVM." ---- Go to their website at: py4j.sourceforge.net/index.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.