0

I am trying to update a library from JDK 8 to JDK 11; there is an access to getClass().getResource("") which is converted to URI would result into the path. Now after updating from Java 8 to 11 it's always returning null. Is there any change on JDK which might have caused this?

 URI resource = Objects.requireNonNull(getClass().getResource(""), "resource").toURI();
sam_haz
  • 189
  • 3
  • 15
  • 2
    `getResource("")` was never guaranteed to work and can fail in older Java versions too, e.g. when the class is in a jar file. You should also keep in mind that `getClass().getResource(…)` may search in an entirely different location when `this` is a subtype of the current class. Usually, that is not intended. – Holger Jun 02 '21 at 12:30
  • @Holger, thank you for your reply; I wanted to get the running jar file uri to process on later; can you please let me know what alternative should I look for in this case? – sam_haz Jun 02 '21 at 12:36
  • @Michael, thanks for your comment. Unfortunately this is not exactly the same question; I followed the other question you mentioned but the recommended approach does not work in my case. – sam_haz Jun 02 '21 at 12:39
  • 1
    Dealing with `URI` is tricky. What are you intending to do with it? Perhaps, there’s a better alternative. – Holger Jun 02 '21 at 12:41
  • The current approach is to copy the resources within the jar to a temporary directory so that can be opened. Can you suggest a better approach? – sam_haz Jun 02 '21 at 13:16
  • 1
    [Use the `FileSystem` API](https://stackoverflow.com/a/36021165/2711488). One thing that always works, is to get the class file of an existing class, e.g. `Foo.class.getResource("Foo.class")`. Use the solution of the linked answer to get a `Path` in a way that works with default filesystem, zip/jar files, as well as module images. Once you have the `Path` for the class file, `getParent()` gives you the directory and operations like `Files.list(…)` or `Files.copy(…)` work smoothly. – Holger Jun 02 '21 at 13:25
  • Unfortunately calling `Foo.class.getResource("Foo.class")` returns null. The approach how it should work is very similar to your recommended; I will get the Path and copy the resources required in a temp directory but I am stuck in the null issue for now. – sam_haz Jun 02 '21 at 13:34
  • 1
    Unless `Foo` is a nested class, `Foo.class.getResource("Foo.class")` should always work—at least with all standard class loaders. – Holger Jun 02 '21 at 14:26
  • In my case it was not a nested class but it was called by jetbrains plugin framework (the app is a jetbrains plugin) so I am not sure which class loader does this get invoked with. I was able to workaround by using a static resource with an absolute path which was able to resolve into the runtime jar file. I am not 100% sure why using class didn't work but my assumption was due to the class loader it was using. – sam_haz Jun 03 '21 at 08:37

0 Answers0