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

执行编译后jar文件报错:java.lang.IllegalAccessError无法访问GIFImageReader

异常根因分析

Caused by: java.lang.IllegalAccessError: class Animation (in unnamed module @0x365608eb) cannot access class com.sun.imageio.plugins.gif.GIFImageReader (in module java.desktop) because module java.desktop does not export com.sun.imageio.plugins.gif to unnamed module

该错误出现在Java 9及以上版本,是Java平台模块系统(JPMS)的访问限制导致的:com.sun.imageio.plugins.gif.GIFImageReader属于JDK内部非公开API,java.desktop模块默认不会将该包下的类暴露给classpath路径下的未命名模块调用,你当前的代码直接实例化了非公开内部类,属于不推荐的API使用方式,因此触发权限报错:

ImageReader ir = new GIFImageReader(new GIFImageReaderSpi());
ir.setInput(inputStream);
解决方案
  • 方案1:使用ImageIO标准API获取GIF读取器(最推荐,无版本兼容问题)
    不要直接调用JDK内部类,通过ImageIO提供的标准查找接口获取对应格式的读取器,代码修改为:
Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("gif");
if (readers.hasNext()) {
    ImageReader ir = readers.next();
    ir.setInput(inputStream);
    // 后续业务逻辑保持不变
}

该写法完全依赖公开API,兼容所有支持GIF读取的JDK版本,不会受模块系统限制影响,也不会在后续JDK版本升级中出现类找不到的问题。

  • 方案2:添加JVM启动参数临时开放访问权限(仅适合临时兼容场景)
    如果当前业务逻辑必须直接使用该内部类,可以在启动jar时添加JVM参数强制导出对应包:
--add-exports java.desktop/com.sun.imageio.plugins.gif=ALL-UNNAMED

完整启动命令示例:

java --add-exports java.desktop/com.sun.imageio.plugins.gif=ALL-UNNAMED -jar your-app.jar

注意该方案属于临时兼容方案,后续JDK版本可能移除该内部类,存在长期兼容性风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 08:27:02