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

Eclipse运行Java代码时出现IllegalAccessError错误如何解决?

解决Java模块访问错误:无法访问java.awt.Rectangle

问题代码

package notes;

import java.util.Random;
import java.awt.Rectangle;
/**
 * 
 */
public class practice {


    public static void main(String[] args) {

        Rectangle box1 = new Rectangle(100, 100, 50, 50);
                System.out.println(box1.width);
        
    }
}

报错信息

Exception in thread "main" java.lang.IllegalAccessError: class notes.practice (in module notes) cannot access class java.awt.Rectangle (in module java.desktop) because module notes does not read module java.desktop
    at notes/notes.practice.main(practice.java:18)

原因

Java 9及以上版本引入了模块化系统,你的项目被识别为自定义模块notes,而java.awt.Rectangle属于系统模块java.desktop,默认自定义模块不会自动依赖该系统模块,因此触发访问权限错误。

解决方案

方案1:关闭模块化(推荐新手)

  • 右键项目 → 属性 → Java Build Path → Libraries
  • 找到并删除项目中的module-info.java文件。这样项目会切换回传统类路径模式,无需额外配置即可访问java.awt包下的类。

方案2:保留模块化并声明依赖

如果需要继续使用模块化,修改项目中的module-info.java,添加对java.desktop模块的依赖声明:

module notes {
    requires java.desktop;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 11:20:04