Scala getClass.getResource() 返回 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12133632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala getClass.getResource() returning null
提问by Tower
I have this code:
我有这个代码:
val url: URL = getClass.getResource("com/mysite/main/test.fxml")
and it always returns null(or Unit). I have only two files in the project:
它总是返回null(或Unit)。我的项目中只有两个文件:
MyProj/src/com/mysite/main/Test.scala
MyProj/src/com/mysite/main/test.fxml
and when I run the Test.scalathe urlvalue is always null.
当我运行时,Test.scala该url值始终为空。
I just tried rebuild the project, I am using IntelliJ IDEA. What am I doing wrong here?
我刚刚尝试重建项目,我正在使用 IntelliJ IDEA。我在这里做错了什么?
回答by Tomasz Nurkiewicz
You have three options:
您有三个选择:
take advantage of relative path to your current package (where
Test.classis):getClass.getResource("test.fxml")you can use absolute path:
getClass.getResource("/com/mysite/main/test.fxml")or load through the
ClassLoader(note that it always start from root):getClass.getClassLoader.getResource("com/mysite/main/test.fxml")
利用当前包的相对路径(在哪里
Test.class):getClass.getResource("test.fxml")您可以使用绝对路径:
getClass.getResource("/com/mysite/main/test.fxml")或加载
ClassLoader(注意它总是从 root 开始):getClass.getClassLoader.getResource("com/mysite/main/test.fxml")
In IntelliJ IDEA, make sure you have added ;?*.fxmlto the:
在 IntelliJ IDEA 中,确保您已添加;?*.fxml到:
Settings(Preferenceson Mac) | Compiler| Resource Patterns.
Settings(Preferences在 Mac 上)| Compiler| 资源模式。
回答by ConorR
Possibly it's not being copied to the bin/ directory from the src/ directory? This happens on recompilation, but if you drop it into the src/ directory after the program is already compiled, the IDE won't know.
可能它没有从 src/ 目录复制到 bin/ 目录?这发生在重新编译时,但如果在程序编译后将其放入 src/ 目录,IDE 将不知道。
回答by cory.todd
Late answer but I just had this same problem. The root cause was an incorrect rootProject.name entry in my settings.gradle. Once I fixed that, cleaned, and rebuilt my resource were able to load using getClass().getResource(). Hopefully that helps somebody.
迟到的答案,但我刚刚遇到了同样的问题。根本原因是我的 settings.gradle 中的 rootProject.name 条目不正确。一旦我解决了这个问题,清理并重建了我的资源就可以使用 getClass().getResource() 加载。希望这可以帮助某人。

