-1

I got code review comment that below line could return NPE

this.getClass().getClassLoader().getResource("").getPath()

As I'm refering self class, is any chance I can get NPE?

I found this answer which says if I load external file then there is NPE possibility, am I right ?

Swapnil Kotwal
  • 5,418
  • 6
  • 48
  • 92
  • 3
    getResource("") -> not sure, but I guess this could. – Stultuske Dec 20 '17 at 10:45
  • can you please answer it why? and how can I overcome it? would be very beneficial for me. – Swapnil Kotwal Dec 20 '17 at 10:47
  • Yes. Read [the documentation](https://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html#getResource(java.lang.String)). http://idownvotedbecau.se/noresearch/ – Boris the Spider Dec 20 '17 at 10:47
  • 1
    you could add a simple null-check – Stultuske Dec 20 '17 at 10:51
  • 1
    The term "resource (name)" is subject to a class loader's implementation. Under the default system class loader and `URLClassLoader`, `getResource("")` will actually return `null` when the loader's search path is either unspecified or does not include any directory entries. Some other loader could prefer to unconditionally return `null` or attach special semantics to the empty resource name or whatever. – Uux Dec 20 '17 at 11:58
  • Can someone help me to load current class path if my expression evaluates into `NPE` – Swapnil Kotwal Dec 21 '17 at 09:31
  • 1
    Your best chances are with `System.getProperty("java.class.path")`, or, if applicable (JDK < 9), `((URLClassLoader) ClassLoader.getSystemClassLoader()).getURLs()`. But there's never 100% guarantee that it won't return `null` in the general case, because it ultimately depends on what/how launches the JVM. – Uux Dec 21 '17 at 13:19

1 Answers1

0

I used below code to avoid NPE

Paths.get("").toAbsolutePath().normalize().toString()

Yes, from comment this JavaDoc is much helpful.

https://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html#getResource(java.lang.String)

getResource
public URL getResource(String name)
Finds the resource with the given name. A resource is some data (images, audio, text, etc) that can be accessed by class code in a way that is independent of the location of the code.
The name of a resource is a '/'-separated path name that identifies the resource.

This method will first search the parent class loader for the resource; if the parent is null the path of the class loader built-in to the virtual machine is searched. That failing, this method will invoke findResource(String) to find the resource.

Parameters:
name - The resource name
Returns:
A URL object for reading the resource, or null if the resource could not be found or the invoker doesn't have adequate privileges to get the resource.
Since:
1.1
Swapnil Kotwal
  • 5,418
  • 6
  • 48
  • 92