You can call a Python method from Java by implementing a Java interface on the python side.

The steps are:

  1. Create an interface in Java, e.g., py4j.examples.Operator
  2. In Python, create a class and inside the class, create a Java class with an "implements" field.
  3. In Python, instantiate a gateway with start_callback_server=True, e.g., gateway = JavaGateway(start_callback_server=True)
  4. In Python, instantiate the class implementing a Java interface and send it to the Java side.
  5. In Java, call the interface.

Example adapted from the Py4J documentation:

Java code:

// File 1
package py4j.examples;

public interface Operator {
        public int doOperation(int i, int j);
        public int doOperation(int i, int j, int k);
}

// File 2
package py4j.examples;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import py4j.GatewayServer;

public class OperatorExample {

    // To prevent integer overflow
    private final static int MAX = 1000;

    public List<Integer> randomBinaryOperator(Operator op) {
        Random random = new Random();
        List<Integer> numbers = new ArrayList<Integer>();
        numbers.add(random.nextInt(MAX));
        numbers.add(random.nextInt(MAX));
        numbers.add(op.doOperation(numbers.get(0), numbers.get(1)));
        return numbers;
    }
}

Python code:

from py4j.java_gateway import JavaGateway

class Addition(object):
    def doOperation(self, i, j, k = None):
        if k == None:
            return i + j
        else:
            return i + j + k

    class Java:
        implements = ['py4j.examples.Operator']

if __name__ == '__main__':
    gateway = JavaGateway(start_callback_server=True)
    operator = Addition()
    operator_example = gateway.jvm.py4j.examples.OperatorExample()

    # "Sends" python object to the Java side.
    numbers = operator_example.randomBinaryOperator(operator) 
Answer from Barthelemy on Stack Overflow
Top answer
1 of 1
13

You can call a Python method from Java by implementing a Java interface on the python side.

The steps are:

  1. Create an interface in Java, e.g., py4j.examples.Operator
  2. In Python, create a class and inside the class, create a Java class with an "implements" field.
  3. In Python, instantiate a gateway with start_callback_server=True, e.g., gateway = JavaGateway(start_callback_server=True)
  4. In Python, instantiate the class implementing a Java interface and send it to the Java side.
  5. In Java, call the interface.

Example adapted from the Py4J documentation:

Java code:

// File 1
package py4j.examples;

public interface Operator {
        public int doOperation(int i, int j);
        public int doOperation(int i, int j, int k);
}

// File 2
package py4j.examples;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import py4j.GatewayServer;

public class OperatorExample {

    // To prevent integer overflow
    private final static int MAX = 1000;

    public List<Integer> randomBinaryOperator(Operator op) {
        Random random = new Random();
        List<Integer> numbers = new ArrayList<Integer>();
        numbers.add(random.nextInt(MAX));
        numbers.add(random.nextInt(MAX));
        numbers.add(op.doOperation(numbers.get(0), numbers.get(1)));
        return numbers;
    }
}

Python code:

from py4j.java_gateway import JavaGateway

class Addition(object):
    def doOperation(self, i, j, k = None):
        if k == None:
            return i + j
        else:
            return i + j + k

    class Java:
        implements = ['py4j.examples.Operator']

if __name__ == '__main__':
    gateway = JavaGateway(start_callback_server=True)
    operator = Addition()
    operator_example = gateway.jvm.py4j.examples.OperatorExample()

    # "Sends" python object to the Java side.
    numbers = operator_example.randomBinaryOperator(operator) 
🌐
Py4j
py4j.org
Welcome to Py4J — Py4J
>>> from py4j.java_gateway import JavaGateway >>> gateway = JavaGateway() # connect to the JVM >>> random = gateway.jvm.java.util.Random() # create a java.util.Random instance >>> number1 = random.nextInt(10) # call the Random.nextInt method >>> number2 = random.nextInt(10) >>> print(number1, number2) (2, 7) >>> addition_app = gateway.entry_point # get the AdditionApplication instance >>> value = addition_app.addition(number1, number2) # call the addition method >>> print(value) 9 · This is the Java program that was executing at the same time (no code was generated and no tool was required to run these programs). The AdditionApplication app instance is the gateway.entry_point in the previous code snippet. Note that the Java program must be started before executing the Python code above.
Discussions

How to call java from python using PY4J - Stack Overflow
You should first start the java program, and then invoke java method from python. py4j doesn't start jvm, it just connects to the already started java process. More on stackoverflow.com
🌐 stackoverflow.com
Both ways, java <=> python, communication using py4j - Stack Overflow
I am using py4j for communication between python and java.I am able to call python method from java side. But from python I am not able to send any object or call java method. Here is the code i have More on stackoverflow.com
🌐 stackoverflow.com
Best way to combine Python and Java?
I've used JPype for a while. It also starts a JVM from python. Once set up, interoperating with Java is transparent. You can start the JVM in such a way that it can be debugged directly using remote debugging tools. More on reddit.com
🌐 r/java
82
60
October 29, 2022
Error with PySpark and Py4J
I was learning Spark and during the installation I got the error of 'Java gateway process exited'. After trying a lot of solutions I finally found a way. I changed the location of my Temp directory under my User Environment Variables. So, the problem was that I had a space in my username, so it was working properly. Don't know if this helps in your case.😅 More on reddit.com
🌐 r/apachespark
25
9
September 5, 2024
🌐
Py4j
py4j.org › advanced_topics.html
3. Advanced Topics — Py4J
Only one Java Thread will be created and no Python thread will be created: The Python client initiates the conversation from Python Thread 1 by calling firstPing() and waits for either a response or a call to execute.
🌐
Py4j
py4j.org › getting_started.html
2. Getting Started with Py4J — Py4J
This short tutorial assumes that you have already installed Py4J and that you are using the latest version. In this tutorial, you will write a simple Stack class in Java and then, you will write a Python program that accesses the stack.
🌐
PyPI
pypi.org › project › py4j
py4j · PyPI
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 ...
      » pip install py4j
    
Published   Jan 15, 2025
Version   0.10.9.9
🌐
Google Groups
groups.google.com › a › py4j.org › g › py4j › c › SNDBGy_6VPw
Calling python from java : py4j.Py4JException: An exception was raised by the Python Proxy. Return M
Hi Sorry I forgot to include the Python code. here it is... from py4j.java_gateway import JavaGateway import os import sys import powerfactory class ToFromjava(object): def runPowerFactory(): try: pyd_PATH = r'C:/Program Files (x86)/DIgSILENT/PowerFactory 15.1/python' sys.path.append(pyd_PATH) app = powerfactory.GetApplication() app.Show() project = app.ActivateProject("Final project(2)") #Nine Bus System prj = app.GetActiveProject() except ValueError: print("Oops! not a valied call...") class Java: implements = ['repastextrun.javaPyCallInt'] if __name__ == '__main__': logger = logging.getLogger("py4j") logger.setLevel(logging.DEBUG) logger.addHandler(logging.StreamHandler()) gateway = JavaGateway(start_callback_server=True) toFromjava = ToFromjava() toFromjava_ex = gateway.jvm.repastextrun.JavaPyCall() toFromjava_ex.CollectDemandData(toFromjava) Thanks Sudheera
🌐
Manmustbecool
manmustbecool.github.io › MyWiki › Wiki › Python › python_java.html
Call Java from Python
from py4j.java_gateway import JavaGateway gateway = JavaGateway() # connect to the JVM random = gateway.jvm.java.util.Random() # create a java.util.Random instance number1 = random.nextInt(10) # call the Random.nextInt method print(number1) AdditionApplication addition_app = new gateway.jvm.AdditionApplication() # get the AdditionApplication instance value = addition_app.addition(4, 5)) # call the addition method print(value)
Find elsewhere
🌐
GitHub
gist.github.com › bartdag › 1070311
Java and Python and Py4J · GitHub
August 24, 2017 - I recently just came across the problem of starting python process from Java. And What i did was using runtime.getRuntime.exec() to launch a new python process to create the JavaGateway, and the rest of it would be same of tutorial on websites, which is just start the Gatewayserver in the following java code. At the very end I would destroy the python process. However, it throws an error: py4j.Py4JException: Error while obtaining a new communication channel at py4j.CallbackClient.getConnectionLock(CallbackClient.java:218) at py4j.CallbackClient.sendCommand(CallbackClient.java:337) at py4j.Call
🌐
Myrobotlab
myrobotlab.org › service › Py4j
Py4j | MyRobotLab
# Py4J also enables Java programs to call back Python objects. Py4J is distributed under the BSD license # Python 2.7 -to- 3.x is supported # In your python 3.x project # pip install py4j # you have full access to mrl instance that's running # the gateway import json import sys from abc import ...
🌐
GitHub
github.com › py4j › py4j
GitHub - py4j/py4j: Py4J enables Python programs to dynamically access arbitrary Java objects · GitHub
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 ...
Starred by 1.3K users
Forked by 231 users
Languages   Java 63.1% | Python 34.8%
🌐
Ptidej Team Blog
blog.ptidej.net › bridging-the-gap-accessing-java-objects-from-python-and-vice-versa
Mind the Gap: Accessing Java Objects from Python and Vice Versa
May 8, 2024 - Traceback (most recent call last): File "", line 1, in File "py4j/java_gateway.py", line 158, in call args_command = ''.join([get_command_part(arg) for arg in args]) File "py4j/java_gateway.py", line 68, in get_command_part command_part = REFERENCE_TYPE + parameter.get_object_id()AttributeError: 'list' object has no attribute 'get_object_id' Below is the structure of the Java project with interfaces that Python must implement.
🌐
Stack Overflow
stackoverflow.com › questions › 44149878 › both-ways-java-python-communication-using-py4j
Both ways, java <=> python, communication using py4j - Stack Overflow
class SimpleHello(object): def sayHello(self, int_value=None, string_value=None): print(int_value, string_value) return "From python to {0}".format(string_value) class Java: implements = ["py4j.examples.IHello"] # Make sure that the python code is started first. # Then execute: java -cp py4j.jar py4j.examples.SingleThreadClientApplication from py4j.java_gateway import JavaGateway, CallbackServerParameters simple_hello = SimpleHello() gateway = JavaGateway( callback_server_parameters=CallbackServerParameters(), python_server_entry_point=simple_hello)
🌐
PyPI
pypi.org › project › jtypes.py4j
jtypes.py4j · PyPI
Py4J also enables Java programs to call back Python objects. Here is a brief example of what you can do with Py4J. The following Python program creates a java.util.Random instance from a JVM and calls some of its methods.
      » pip install jtypes.py4j
    
Published   Nov 13, 2018
Version   0.10.8a1
🌐
Py4j
py4j.org › faq.html
6. Frequently Asked Questions — Py4J
Each gateway connection is executed in is own thread (e.g., each time a Python thread calls a Java method) so if multiple Python threads/processes/programs are connected to the same gateway, i.e., the same address and the same port, multiple threads may call the entry point’s methods concurrently.
🌐
Liacs
rsewiki.liacs.nl › calling_java_from_python
Calling Java from Python [LIACS Wiki]
April 1, 2021 - The Python code will connect to this running application to interact with the JVM. ... from py4j.java_gateway import JavaGateway gateway = JavaGateway() # connect to the JVM random = gateway.jvm.java.util.Random() # create a java.util.Random instance number1 = random.nextInt(10) # call the Random.nextInt method number2 = random.nextInt(10) gateway_app = gateway.entry_point # get the GatewwayApplication instance value = gateway_app.called_from_python(number1, number2) # call the addition method print(value)
🌐
SourceForge
sourceforge.net › home › browse › py4j › mailing lists
Re: [Py4j-users] Calling Python from Java side? | Py4J
February 18, 2015 - py4j-users · View entire thread · Thanks for helping keep SourceForge clean.
🌐
Reddit
reddit.com › r/java › best way to combine python and java?
r/java on Reddit: Best way to combine Python and Java?
October 29, 2022 -

My project uses some packages that are available only in Python and heavily rely on C libraries. The project also greatly benefits from Java libraries and the JVM. What's the optimal way to call Python functions from Java?

I tried:

  1. Small web-services: overhead to serialize data, start and stop the services. Also debugging is harder and implementing each new function is now double the effort.

  2. Jpy: a library that runs an interpreter in the JVM. Spare the service start/stop, but: isn't really feasible for more than a single-liner, data translation between Java and Python is cumbersome, and I also encountered runtime segmentation fault errors.

Any other options?

The project is in the machine-learning domain, so involves exchanging large numeric arrays and text. In some cases the execution switches back and forth between the platforms.

🌐
Tejass Publisheers
ijarcce.com › papers › using-py4j-for-java-python-communication
Using Py4J for Java-Python Communication - Peer-reviewed Journal
May 31, 2023 - One of the main benefits of using Py4J is that it allows access to Java classes and libraries that are not natively available in Python. The Py4J module establishes a bridge between Python and Java, allowing Python code to call Java methods and access Java objects.
🌐
GeeksforGeeks
geeksforgeeks.org › java › integrating-java-with-python
Integrating Java with Python - GeeksforGeeks
July 23, 2025 - First, the Python program should be able to access the Java Virtual Machine (JVM) running the Java program. This requires an instance of the GatewayServer class available in the library py4j that makes this communication possible.