Two java files. Getting IllegalAccessError when running class with main method trying to access a method from the other file

前端 未结 3 371
野的像风
野的像风 2020-12-22 08:12

Learning Java. I have two files, each containing one java class. When I run the file with the main method, I get the following error:

Exception in threa

3条回答
  •  被撕碎了的回忆
    2020-12-22 08:43

    Actual Issue

    I got this exact same error* doing something very silly:

    I tried to run the file as java {main-class}.java. That simple!

    Instead, be sure to run it simply as java {main-class}.


    *Specifically, the error format I had, like yours:

    Exception in thread "main" java.lang.IllegalAccessError: failed to access class {pack.other-class} from class {pack.main-class} ({pack.other-class} is in unnamed module of loader 'app'; {pack.main-class} is in unnamed module of loader com.sun.tools.javac.launcher.Main$MemoryClassLoader @29f69090)

      at {pack.main-class}.{who-cares-where}
      at {pack.main-class}.{who-cares-why}
                 . . .


    Extra Advice

    You can get a similarly annoying error on the same issue, namely inability to access packages in the same directory, if you only compile your {main-class}.

    So instead of javac {directory}/{main-class}.java

    Be sure to compile all of them at the same time, so there's no issue in cross-referencing:
      javac {directory}/*.java


    OP Specific

    This would just be a silly command-line mistake. If it's occurring in IntelliJ as well, as you say, this isn't your issue. However, I hope it's at least helpful to the others who come across your question with this error!

提交回复
热议问题