英文:
Toolkit.getImage(URL url) works with Java 8 but fails with Java 11
问题
我在一个Java SE Swing应用程序中遇到了问题。它在Java 8和11上都可以编译通过,但在后者上在以下代码行中出现问题:
URL url = Object.class.getResource("/org/mozillatranslator/resource/mt_icon_small.gif");
Toolkit tk = Toolkit.getDefaultToolkit();
Image img = tk.getImage(url); // 引发运行时异常
并伴有以下异常:
Caused by: java.lang.NullPointerException
at java.desktop/sun.awt.SunToolkit.getImageFromHash(SunToolkit.java:653)
at java.desktop/sun.awt.SunToolkit.getImage(SunToolkit.java:689)
at org.mozillatranslator.gui.MainWindow.loadIcon(MainWindow.java:232)
如我所述,这行代码在Java 8上运行正常,但在具有相同JAR的Java 11上失败。我已经搜索了Java 8以后版本中的行为更改,但没有找到任何相关信息。是否有人遇到过类似的情况,或者能否提供可能的解决方法?
英文:
I'm having a problem with a Java SE Swing application. It compiles fine on both Java 8 and 11, but it fails on the latter in these lines:
URL url = Object.class.getResource("/org/mozillatranslator/resource/mt_icon_small.gif");
Toolkit tk = Toolkit.getDefaultToolkit();
Image img = tk.getImage(url); // Raises runtime exception
with this exception:
Caused by: java.lang.NullPointerException
at java.desktop/sun.awt.SunToolkit.getImageFromHash(SunToolkit.java:653)
at java.desktop/sun.awt.SunToolkit.getImage(SunToolkit.java:689)
at org.mozillatranslator.gui.MainWindow.loadIcon(MainWindow.java:232)
As I've said, the line works on Java 8, but fails on Java 11 with the exact same JAR. I've searched for a change in Java behavior in versions beyond 8, but I haven't found anything. Has anyone suffered a similar situation, or can suggest any possible workarounds?
答案1
得分: 2
使用以下代码:
URL url = <YourClassName>.class.getResource("/org/mozillatranslator/resource/mt_icon_small.gif");
或者
URL url = Thread.currentThread()
.getContextClassLoader()
.getResource("org/mozillatranslator/resource/mt_icon_small.gif");
`Object`是由引导类加载器加载的(参考[官方文档](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Class.html#getResource(java.lang.String))),因此`Object.class.getResource()`使用[系统类加载器](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/ClassLoader.html#getSystemResource(java.lang.String))。
使用空字符串参数来检查返回值:`Object.class.getResource("")`,`YourClass.class.getResource("")`和`Thread.currentThread().getContextClassLoader().getResource("")`。
英文:
Use
URL url = <YourClassName>.class.getResource("/org/mozillatranslator/resource/mt_icon_small.gif");
or
URL url = Thread.currentThread()
.getContextClassLoader()
.getResource("org/mozillatranslator/resource/mt_icon_small.gif");
Object
is loaded by bootstrap class loader, so Object.class.getResource()
uses system class loader.
Check return values with empty string parameter; Object.class.getResource("")
, YourClass.class.getResource("")
, and Thread.currentThread().getContextClassLoader().getResource("")
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论