this.getClass()。getClassLoader()。getResource(“”)。getPath()是否可以在这里进行NPE?

时间:2017-12-20 10:44:29

标签: java classloader absolute-path file-location

我收到了代码审核评论,下面一行可以返回NPE

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

当我提到自我上课时,我是否有机会获得NPE

我发现this answer表示如果我加载外部文件然后有NPE可能性,我是对的吗?

1 个答案:

答案 0 :(得分:0)

我使用下面的代码来避免NPE

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

是的,从评论这个JavaDoc非常有用。

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