2017-12-20 36 views
-1

는 내가 자기 클래스를 다스 려 해요로 선 아래 내가 NPE을 얻을 수있는 기회이며, NPEthis.getClass(). getClassLoader(). getResource (""). getPath()는 NPE가 가능합니까?

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

를 반환 할 수 코드 검토 의견을 가지고?

내가 외부 파일을로드하면 NPE 가능성이 있다고 말하는 this answer이 발견되었습니다. 맞습니까?

+3

의 getResource ("") -> 확실하지 않은,하지만 난이있을 것 같아요. – Stultuske

+0

왜 대답 해 주실 수 있습니까? 어떻게 그것을 극복 할 수 있습니까? 나를 위해 매우 유익 할 것입니다. –

+0

예. [설명서] (https://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html#getResource (java.lang.String))를 읽으십시오. http://idownvotedbecau.se/noresearch/ –

답변

0

나는이의 JavaDoc가 도움이 많이는 의견에서, 예 NPE

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

을 방지하기 위해 코드 아래 사용.

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