MyClass.class.getClassLoader().getResource(“”).getPath() throws NullPointerException

谁都会走 提交于 2019-12-22 18:00:40

问题


I have code that is running correctly on a development machine but throws a NullPointerException when installed in a production environment. The line that throws the exception is the following:

MyClass.class.getClassLoader().getResource("").getPath();

So I split this into multiple lines of code to see exactly which call was returning null, like this:

ClassLoader cl = MyClass.class.getClassLoader();
URL url = cl.getResource("");
String path = url.getPath();

Now the url.getPath() call is throwing the NullPointerException, meaning that cl.getResource("") is returning null.

Can anyone tell me how this call can ever return null?


回答1:


The implementation of getResource is different for different ClassLoader implementations.

While this might reliably work on your local machine, it is not guaranteed to be successful on other ClassLoader implementations.

So expect other ClassLoaders to behave differently (especially if you execute that code inside a Application Server, WebStart Launcher or any environment that has some security restrictions).




回答2:


It's clearly said in the javadocs for the ClassLoader#getResource(String name) method.

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.

Obviously, there is no resource with name "" and therefore null is returned.;




回答3:


The url is null, so you can't call getPath() on it. Calling getResource with a "" parameter will, at in my understanding always return null, so this is guaranteed to blow up.




回答4:


getClassLoader public ClassLoader getClassLoader() Returns the class loader for the class. Some implementations may use null to represent the bootstrap class loader. This method will return null in such implementations if this class was loaded by the bootstrap class loader.

Read above lines.



来源:https://stackoverflow.com/questions/19314531/myclass-class-getclassloader-getresource-getpath-throws-nullpointerexcep

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!