Search code examples
javaclassloaderabsolute-pathfile-location

this.getClass().getClassLoader().getResource("").getPath() is NPE possible here?


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 ?


Solution

  • 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