I've recently upgraded to JDK 9 and Eclipse complains that sun.misc.Launcher
cannot be imported. It seems that sun.misc.Launcher
is unsafe.
I'm looking for an alternative to replace this line of code in my project.
final URL url = Launcher.class.getResource("/");
Any help would be appreciated.
Update: the more complete version of the above block of code is:
final URL url = Launcher.class.getResource("/");
final File fs = new File(url.toURI());
for (File f : fs.listFiles()) {
System.out.println(f.getAbsolutePath());
}
This is to print all the files in the src
folder when program is launched in IDE.
The JDK.Unsupported Module Sun.misc.Unsafe is now available in the jdk.unsupported module. This module is present in the full JRE and JDK images. Here is the module declaration for jdk.unsupported:
Earlier versions don’t work with Java 9. Sun.misc.Unsafe is now available in the jdk.unsupported module. This module is present in the full JRE and JDK images. As you can see, sun.misc is exported. I have a sample project with a package java9unsafe and a module with the same name.
The reason sun.misc.Unsafe can't simply be dumped, he told me in an e-mail, is that it provides a number of functionalities that aren't available through any of the standard classes in OpenJDK. " [sun.misc.Unsafe] should be cleaned up and the safe parts should get standardized," Verburg said. "The rest should be removed!
I have a sample project with a package java9unsafe and a module with the same name. To use Unsafe, you need to add jdk.unsupported to your code’s module declaration: Fortunately, IDEA will detect the declaration if missing and suggest adding it for you when you hover over your import statement. Then you can use Unsafe.
Class.getResource
method can be invoked on any Class
final URL url = ClassInTheCurrentModule.class.getResource("/");
UPDATE
Edited based on Feedback from members
Calling the Class.getResource
from any of the class in the module whose classes are being tried to access should work fine.
final URL url = ClassInTheCurrentModule.class.getResource("/");
The reason why the answer by shazin might return null
is probably that with ClassLoader
being a caller for the getResource
call:
returns
null
when the resource is a non-".class" resource in a package that is not open to the caller's module.
Since ClassLoader
belongs to the package java.lang
in the module java.base
to which your module might not be open.
Also, do note the resolution of the getResource
is split further for named and unnamed modules.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With