
在现代软件开发中,跨语言集成是常见的需求,尤其是在机器学习领域。许多高效的机器学习模型和库都是用 python 开发的,但核心业务逻辑可能运行在 java 平台上。为了在 java 应用中利用这些 python 模型,我们需要一种可靠的机制来实现两者之间的通信和调用。jython 作为 python 在 java 虚拟机(jvm)上的实现,提供了一种直接在 java 环境中执行 python 代码的有效途径。
Jython 是 Python 语言在 Java 平台上的一个实现。它允许开发者用 Python 语言编写程序,并在 JVM 上运行。Jython 的主要优势在于能够无缝地与 Java 代码进行交互:Python 代码可以导入和使用 Java 类库,反之,Java 代码也可以实例化和调用 Python 对象。这种双向互操作性使得 Jython 成为在 Java 应用中集成 Python 模块,特别是机器学习模型的理想选择。
其核心原理是,Jython 解释器在 JVM 内部运行,将 Python 代码编译成 Java 字节码,或者直接解释执行。通过 Jython,Java 程序可以获得一个 Python 解释器实例,然后利用该实例加载并执行 Python 脚本,进而获取 Python 对象(如模型实例或函数)的引用,并像调用普通 Java 对象一样调用其方法。
在 Java 应用中集成 Python 机器学习模型主要涉及以下几个步骤:
首先,我们需要一个简单的 Python 分类器模型。为了演示目的,我们创建一个不依赖 C 扩展的纯 Python 类。
立即学习“Java免费学习笔记(深入)”;
classifier_model.py
# classifier_model.py
class SimpleClassifier:
    """
    一个简单的分类器类,用于演示在Java中调用Python对象。
    """
    def __init__(self, offset=1):
        self.offset = offset
    def classify(self, input_value: int) -> int:
        """
        根据输入值进行分类,这里只是简单地加上一个偏移量。
        :param input_value: 输入的整数值
        :return: 分类结果
        """
        print(f"Python: Classifying input {input_value} with offset {self.offset}")
        return input_value + self.offset
# 在脚本中实例化分类器,以便Java可以直接获取其引用
# 注意:在实际应用中,您可能需要一个工厂函数来创建模型实例
# 或者在Java中通过反射调用Python类的构造函数。
classifier_instance = SimpleClassifier(offset=10)
# 如果需要,也可以定义一个独立的函数
def predict_score(value: int) -> int:
    """
    一个独立的预测函数。
    """
    return value * 2接下来,我们编写 Java 代码来加载并调用上述 Python 模型。
首先,确保你的项目中已经添加了 Jython 的依赖。如果你使用 Maven,可以在 pom.xml 中添加:
<dependency>
    <groupId>org.python</groupId>
    <artifactId>jython-standalone</artifactId>
    <version>2.7.3</version> <!-- 请使用最新的稳定版本 -->
</dependency>如果你是手动添加 JAR 包,请下载 jython-standalone-2.7.3.jar(或最新版本)并将其添加到项目的类路径中。
src/main/java/com/example/Main.java
package com.example;
import org.python.core.PyException;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
public class Main {
    public static void main(String[] args) {
        // 创建一个 Python 解释器实例
        // PythonInterpreter interp = new PythonInterpreter(); // 默认构造函数
        // 也可以配置解释器,例如设置sys.path等
        PythonInterpreter interp = new PythonInterpreter();
        try {
            // 加载并执行 Python 脚本文件
            // 确保 classifier_model.py 在 Java 应用程序的类路径或工作目录下
            // 或者提供完整路径
            System.out.println("Java: Executing Python script 'classifier_model.py'...");
            interp.execfile("classifier_model.py");
            System.out.println("Java: Python script executed.");
            // 1. 获取 Python 中定义的类实例 (classifier_instance)
            System.out.println("Java: Getting Python object 'classifier_instance'...");
            PyObject classifier = interp.get("classifier_instance");
            if (classifier == null) {
                System.err.println("Java: Failed to get 'classifier_instance' from Python interpreter.");
                return;
            }
            // 准备输入参数
            int inputValue = 5;
            PyInteger pyInput = new PyInteger(inputValue);
            // 调用 Python 对象的方法
            System.out.println("Java: Invoking Python method 'classify' with input " + inputValue + "...");
            PyObject result = classifier.invoke("classify", pyInput);
            // 将 Python 返回值转换为 Java 类型
            int classifiedValue = result.asInt();
            System.out.println("Java: Python 'classify' method returned: " + classifiedValue);
            System.out.println("Expected: " + (inputValue + 10)); // 因为Python中设置了offset=10
            System.out.println("\n--- Demonstrating calling a standalone function ---");
            // 2. 获取 Python 中定义的独立函数 (predict_score)
            PyObject predictFunction = interp.get("predict_score");
            if (predictFunction == null) {
                System.err.println("Java: Failed to get 'predict_score' from Python interpreter.");
                return;
            }
            int scoreInput = 7;
            PyInteger pyScoreInput = new PyInteger(scoreInput);
            System.out.println("Java: Invoking Python function 'predict_score' with input " + scoreInput + "...");
            PyObject scoreResult = predictFunction.invoke(pyScoreInput);
            int predictedScore = scoreResult.asInt();
            System.out.println("Java: Python 'predict_score' function returned: " + predictedScore);
            System.out.println("Expected: " + (scoreInput * 2));
        } catch (PyException e) {
            System.err.println("Java: An error occurred during Python execution: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // 关闭解释器,释放资源
            interp.cleanup();
        }
    }
}预期输出示例:
Java: Executing Python script 'classifier_model.py'... Java: Python script executed. Java: Getting Python object 'classifier_instance'... Java: Invoking Python method 'classify' with input 5... Python: Classifying input 5 with offset 10 Java: Python 'classify' method returned: 15 Expected: 15 --- Demonstrating calling a standalone function --- Java: Getting Python object 'predict_score'... Java: Invoking Python function 'predict_score' with input 7... Java: Python 'predict_score' function returned: 14 Expected: 14
Jython 为 Java 应用程序提供了一种直接、简洁的方式来集成和调用纯 Python 代码,特别适用于那些不依赖 C 扩展的机器学习模型或业务逻辑。通过创建 Python 解释器、执行 Python 脚本并获取 Python 对象的引用,Java 开发者可以无缝地利用 Python 生态系统的优势。然而,在选择 Jython 方案时,务必考虑其对 C 扩展的限制以及潜在的性能影响,并根据实际需求权衡是否采用其他更适合的跨语言集成策略。
以上就是使用 Jython 在 Java 应用中集成 Python 机器学习模型的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号