Issue
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?
Solution
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("")
.
Answered By - DEWA Kazuyuki - 出羽和之
Answer Checked By - Pedro (JavaFixing Volunteer)