杰瑞科技汇

Python与Java包管理如何协同?

Of course! The term "Java packages" in the context of Python can refer to two main, very different things:

Python与Java包管理如何协同?-图1
(图片来源网络,侵删)
  1. Running Java code and using Java libraries from Python. This is about interoperability.
  2. Python packages that are named like Java packages (e.g., java.lang), which is a convention used by some tools, most notably Jython.

Let's break down both scenarios.


Scenario 1: Running Java from Python (The Most Common Need)

This is the most frequent reason a Python developer would ask about "Java packages". You have a Python application, but you need to use a specific Java library (a .jar file) that doesn't have a Python equivalent.

There are two excellent ways to achieve this:

Method A: Using JPype1 (The Modern, Recommended Approach)

JPype1 is a project to enable Python to access Java classes. It's a mature, actively maintained library that is the standard for this kind of interoperability.

Python与Java包管理如何协同?-图2
(图片来源网络,侵删)

Key Concepts:

  • JVM: You start a Java Virtual Machine (JVM) from your Python script.
  • Classpath: You add your Java .jar files to the JVM's classpath, making them available for import.
  • Mapping: JPype maps Java classes and objects to Python objects, and Python types to Java types.

Installation:

pip install JPype1

Example: Using the Apache Commons Lang library

Let's say you want to use the StringUtils class from the Apache Commons Lang library.

Python与Java包管理如何协同?-图3
(图片来源网络,侵删)
  1. Get the JAR file: Download the commons-lang3-3.12.0.jar from the Apache Commons Lang download page.

  2. Write the Python code:

    import jpype
    import jpype.imports
    from jpype.types import *
    # Define the path to your JAR file
    jar_path = "path/to/your/commons-lang3-3.12.0.jar"
    # Start the JVM. You need to specify the classpath.
    # The '.' adds the current directory to the classpath.
    jpype.startJVM(classpath=[jar_path])
    # Now you can import Java classes directly!
    # The 'from jpype.imports import *' is a convenience for this.
    from org.apache.commons.lang3 import StringUtils
    # Use the Java class just like a Python module
    is_blank = StringUtils.isBlank("  ")
    is_not_blank = StringUtils.isNotBlank("hello")
    print(f"Is '  ' blank? {is_blank}")  # Output: Is '  ' blank? True
    print(f"Is 'hello' blank? {is_not_blank}") # Output: Is 'hello' blank? False
    # You can also create Java objects
    j_list = jpype.JArray(jpype.JString)(["apple", "banana", "cherry"])
    joined = StringUtils.join(j_list, ", ")
    print(f"Joined list: {joined}") # Output: Joined list: apple, banana, cherry
    # Shut down the JVM when you're done
    jpype.shutdownJVM()

Method B: Using Py4J (For Running Python from Java)

Py4J takes the opposite approach. It allows a Java application to launch a Python interpreter and call Python functions. This is less common for a Python-first developer but is very powerful in data science pipelines (e.g., a Java-based Spark driver calling Python UDFs).

The key difference is that the JVM is started by the Java application, and the Python side acts as a server that the Java application connects to.


Scenario 2: Python Packages Named Like Java Packages

This is a much more niche topic and almost exclusively relates to Jython.

What is Jython?

Jython is an implementation of the Python programming language written in 100% Java. It runs on the Java Platform and compiles Python source code to Java bytecode.

Key Implications:

  • You can use any Python library that is written in pure Python or has a Jython-compatible backend.
  • You can import and use any Java class directly, as if it were a Python module. This is where the "Java packages" naming convention comes into play.

Example in Jython:

Because Jython is running on the JVM, you can import Java packages directly. This looks exactly like the JPype example but doesn't require any external library setup (beyond running Jython itself).

# This code would be run with the 'jython' interpreter, not the standard 'python' interpreter.
# No need for JPype or a classpath setup if the classes are on the standard JVM path.
from java.lang import System
from java.util import Date
# Use the Java classes
current_time = Date()
System.out.println(f"Current time from Java: {current_time}")
# You can also call Java static methods
print(f"Java version: {System.getProperty('java.version')}")
# You can instantiate Java objects
ArrayList = java.util.ArrayList
my_list = ArrayList()
my_list.add("Hello from Python!")
my_list.add("Running on the JVM.")
print(f"Java ArrayList contents: {my_list}")

Summary and Comparison

Feature JPype1 Jython
Purpose Call Java from Python. Run the Python language on the JVM.
How it Works Starts a JVM from a Python script. A Python interpreter implemented in Java.
Setup pip install JPype1. Requires managing a classpath. Install Jython. Works within any standard Java environment.
Use Case Integrating a specific Java library into an existing Python application. Developing Python applications that need deep, seamless integration with the Java ecosystem, or running Python on a Java server.
Performance Good. Generally slower than CPython due to being on the JVM, but offers unique integration benefits.
Python Version Works with modern CPython (2.7, 3.6+). Lags behind CPython in version support (currently Jython 2.7.3 is the latest stable release).

Conclusion

When a Python developer mentions "Java packages", they are most likely trying to integrate a Java library into their Python project.

  • For this, use JPype1. It's the modern, standard, and most flexible solution.
  • If your entire application needs to run on the JVM and you want to use Python, or if you are working in an environment where Jython is already the standard, then Jython is the answer.
分享:
扫描分享到社交APP
上一篇
下一篇