The interoperability between Python and Java can be achieved in the following ways:
1. Subprocess call
Principle: Call a Java program through Python's subprocess module, pass parameters and capture output.
Applicable scenario: Simple script calls, no complex interactions are required.
Python calls Java example
import subprocess # Define Java classpath and class namejava_class_path = "" java_class_name = "" # Execute Java program and pass parametersresult = ( ["java", "-cp", java_class_path, java_class_name, "arg1", "arg2"], capture_output=True, text=True ) print("Java Output:", ) print("Java Error:", )
Notes:
Start the Java process and wait for the result.
capture_output=True Captures standard output and error streams.
text=True Converts the output to a string (Python 3.7+).
2. Jython
Principle: Jython is a Java implementation of Python, allowing Python scripts to be run directly in the JVM.
Applicable scenarios: Deep integration of JVM environment is required (Python is supported only).
Java calls Python (Jython example)
import ; public class JythonDemo { public static void main(String[] args) { PythonInterpreter interpreter = new PythonInterpreter(); ("print('Hello from Python!')"); ("path/to/your_script.py"); } }
Notes:
Need to be added to the classpath of the Java project.
Jython's Python version is poorly compatible (Python is supported only).
3. JPype
Principle: Start the JVM through JPype and directly call the Java class in Python.
Applicable scenarios: high-performance interaction, you need to directly access Java classes and methods.
Python calls Java (JPype example)
import jpype # Start the JVM (requires the JDK path)( (), "-=", convertStrings=False ) # Import Java classesHelloWorld = ("") instance = HelloWorld() # Call Java methodsoutput = ("World") print("Java Method Output:", output) # Close JVM()
Notes:
startJVM Starts the JVM and loads the specified classpath.
JClass imports Java classes, convertStrings controls automatic conversion of strings.
Need to install JPype: pip install jpype1.
4. Py4J
Principle: Py4J starts the gateway server on the Java side, and Python calls Java methods through a TCP connection.
Applicable scenarios: complex interaction, support callback functions.
Java side (GatewayServer)
import ;public class JavaApp { public String greet(String name) { return "Hello, " + name + "!"; } public static void main(String[] args) { GatewayServer server = new GatewayServer(new JavaApp()); (); } }
Python
from py4j.java_gateway import JavaGateway # Connect to Java gatewaygateway = JavaGateway() java_app = gateway.entry_point # Call Java methodsmessage = java_app.greet("Python") print("Java Response:", message)
Notes:
Java side needs to be introduced.
Python side installation Py4J: pip install py4j.
The default port of GatewayServer is 25333.
5. REST API
Principle: Expose Java services to REST APIs, and Python calls them via HTTP requests.
Applicable scenarios: Cross-language microservice architecture.
Java side (Spring Boot)
@RestController public class ApiController { @GetMapping("/greet") public String greet(@RequestParam String name) { return "Hello, " + name; } }
Python side (Requests)
import requests response = ("http://localhost:8080/greet", params={"name": "Python"}) print("API Response:", )
6. Apache Thrift/gRPC
Principle: Define interfaces through IDL to generate cross-language client and server code.
Applicable scenarios: high-performance, strong-type interface communication.
Example steps
- Define the .proto file.
- Generate Java and Python code.
- Implement server (Java) and client (Python).
7. Method comparison
method | performance | Complexity | Applicable scenarios |
---|---|---|---|
Subprocess call | Low | Low | Simple script |
JPype | high | middle | Tightly integrated, calling Java directly |
Py4J | middle | middle | Complex interaction, support callbacks |
REST/gRPC | Medium-high | high | Distributed systems, microservices |
8. Summary
- Lightweight call: Subprocess or file exchange.
- Deep integration: JPype (Python call Java) or Py4J (bidirectional call).
- Distributed Systems:REST API or gRPC.
This is the article about how to compare the methods and performance of Python and Java interactions. For more related Python Java interaction content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!