2017-12-20 9 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 
関連する問題