You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何阻止Py4J复用旧版本JAR?解决旧代码缓存问题

Py4J调用旧Java代码无法更新的问题解决

环境信息

  • Python 3.9.17(通过asdf+poetry管理)
  • Java 17(通过Maven构建JAR)

初始运行代码

Python端代码

from py4j.java_gateway import JavaGateway
gateway = JavaGateway.launch_gateway()
example = gateway.entry_point
results = example.foo()
print(results) # 输出 "foo"

Java端代码

package foo;
import py4j.GatewayServer;
import java.io.IOException;

public class Example {

    public static void main(String[] args) throws IOException {
        GatewayServer gatewayServer = new GatewayServer(new Example());
        gatewayServer.start();
        System.out.println("Py4J Gateway Server Started");
    }

    public String foo() {
        return "foo";
    }
}

修改后的代码

更新Java代码,移除foo()方法,新增带参数的bar()方法:

package foo;
import py4j.GatewayServer;
import java.io.IOException;

public class Example {

    public static void main(String[] args) throws IOException {
        GatewayServer gatewayServer = new GatewayServer(new Example());
        gatewayServer.start();
        System.out.println("Py4J Gateway Server Started");
    }

    public String bar(String input) {
        return input;
    }
}

问题现象

重新构建Java JAR并启动后,运行Python代码出现异常:

from py4j.java_gateway import JavaGateway
gateway = JavaGateway.launch_gateway()
example = gateway.entry_point
results = example.foo()
print(results) # 居然还输出 "foo"
results = example.bar("bar") # 报错:py4j.protocol.Py4JError: An error occurred while calling t.bar. Trace: py4j.Py4JException: Target Object ID does not exist for this gateway :t

已尝试的操作:

  • 杀死所有Java进程
  • 删除旧版本JAR文件

解决方案

  1. 显式指定新版本JAR路径
    直接在Python代码里指定Maven构建好的最新JAR绝对路径,避免Py4J调用旧缓存:

    gateway = JavaGateway.launch_gateway(jarpath="/your/project/path/target/example.jar")
    

    注意替换成你本地实际的JAR路径,通常Maven构建的JAR在项目根目录的target/文件夹下。

  2. 清理Maven构建缓存
    执行Maven清理命令,彻底删除旧构建产物后重新打包:

    mvn clean install
    

    这会清空target/目录,重新生成包含最新代码的JAR。

  3. 对齐Py4J版本
    确保Python环境的Py4J版本和Java端依赖的Py4J版本完全一致:

    • 用poetry查看当前Python环境的Py4J版本:
      poetry show py4j
      
    • 查看Java项目pom.xml里的Py4J依赖版本,不一致的话更新Python端:
      poetry add py4j==<对应版本号>
      
  4. 指定新端口启动网关
    若旧端口残留连接状态,可指定新端口规避:

    • Python端:
      gateway = JavaGateway.launch_gateway(jarpath="/path/to/new.jar", port=25335)
      
    • Java端同步修改端口:
      GatewayServer gatewayServer = new GatewayServer(new Example(), 25335);
      

内容的提问来源于stack exchange,提问作者Adam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 03:42:49